@bernierllc/email-service 6.0.9 → 6.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/email-service.d.ts +45 -0
- package/dist/email-service.js +833 -0
- package/dist/errors.d.ts +52 -0
- package/dist/errors.js +72 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +10 -0
- package/dist/types.d.ts +242 -0
- package/dist/types.js +30 -0
- package/package.json +6 -6
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { EmailServiceConfig, EmailRequest, SendEmailResult, EmailTemplate, TemplateCreateRequest, TemplateUpdateRequest, DeliveryRecord, DeliveryStats, Subscriber, SubscriberCreateRequest, SubscriberUpdateRequest, SubscriberList, WebhookEvent, WebhookHandler, MagicLinkEmail, MagicLinkResult } from './types.js';
|
|
2
|
+
export declare class EmailService {
|
|
3
|
+
private db;
|
|
4
|
+
private queue?;
|
|
5
|
+
private templateEngine;
|
|
6
|
+
private emailSenders;
|
|
7
|
+
private logger;
|
|
8
|
+
private config;
|
|
9
|
+
private webhookHandlers;
|
|
10
|
+
private templateCache;
|
|
11
|
+
private retryStorage;
|
|
12
|
+
private retryMetrics?;
|
|
13
|
+
constructor(config: EmailServiceConfig);
|
|
14
|
+
private initializeProviders;
|
|
15
|
+
initialize(): Promise<void>;
|
|
16
|
+
private createTables;
|
|
17
|
+
send(request: EmailRequest): Promise<SendEmailResult>;
|
|
18
|
+
private scheduleEmail;
|
|
19
|
+
sendBulk(requests: EmailRequest[]): Promise<SendEmailResult[]>;
|
|
20
|
+
createTemplate(request: TemplateCreateRequest): Promise<EmailTemplate>;
|
|
21
|
+
getTemplate(id: string): Promise<EmailTemplate | null>;
|
|
22
|
+
updateTemplate(id: string, update: TemplateUpdateRequest): Promise<EmailTemplate>;
|
|
23
|
+
deleteTemplate(id: string): Promise<boolean>;
|
|
24
|
+
private renderTemplate;
|
|
25
|
+
private extractVariables;
|
|
26
|
+
getDelivery(id: string): Promise<DeliveryRecord | null>;
|
|
27
|
+
trackOpen(deliveryId: string): Promise<void>;
|
|
28
|
+
trackClick(deliveryId: string): Promise<void>;
|
|
29
|
+
getDeliveryStats(startDate?: Date, endDate?: Date): Promise<DeliveryStats>;
|
|
30
|
+
private parseDeliveryRecord;
|
|
31
|
+
createSubscriber(request: SubscriberCreateRequest): Promise<Subscriber>;
|
|
32
|
+
getSubscriber(id: string): Promise<Subscriber | null>;
|
|
33
|
+
updateSubscriber(id: string, update: SubscriberUpdateRequest): Promise<Subscriber>;
|
|
34
|
+
unsubscribe(email: string): Promise<boolean>;
|
|
35
|
+
private parseSubscriber;
|
|
36
|
+
createList(name: string, description?: string): Promise<SubscriberList>;
|
|
37
|
+
registerWebhookHandler(event: string, handler: WebhookHandler): void;
|
|
38
|
+
handleWebhook(event: WebhookEvent): Promise<void>;
|
|
39
|
+
shutdown(): Promise<void>;
|
|
40
|
+
private generateId;
|
|
41
|
+
sendMagicLink(config: MagicLinkEmail): Promise<MagicLinkResult>;
|
|
42
|
+
private createDefaultMagicLinkHtml;
|
|
43
|
+
private createDefaultMagicLinkText;
|
|
44
|
+
private sendWithRetry;
|
|
45
|
+
}
|
|
@@ -0,0 +1,833 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright (c) 2025 Bernier LLC
|
|
3
|
+
|
|
4
|
+
This file is licensed to the client under a limited-use license.
|
|
5
|
+
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
+
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
+
*/
|
|
8
|
+
import { DatabaseManager } from '@bernierllc/database-adapter';
|
|
9
|
+
import { QueueManager, JobPriority } from '@bernierllc/queue-manager';
|
|
10
|
+
import { TemplateEngine } from '@bernierllc/template-engine';
|
|
11
|
+
import { EmailSender } from '@bernierllc/email-sender';
|
|
12
|
+
import { Logger, LogLevel } from '@bernierllc/logger';
|
|
13
|
+
import { generateJWT } from '@bernierllc/crypto-utils';
|
|
14
|
+
import { calculateRetryDelay, shouldRetry } from '@bernierllc/retry-policy';
|
|
15
|
+
import { createRetryState, MemoryRetryStateStorage } from '@bernierllc/retry-state';
|
|
16
|
+
import { MetricsCollector } from '@bernierllc/retry-metrics';
|
|
17
|
+
import { EmailServiceError, ProviderError, TemplateError, DeliveryError, DeliveryStatus } from './types.js';
|
|
18
|
+
export class EmailService {
|
|
19
|
+
db;
|
|
20
|
+
queue;
|
|
21
|
+
templateEngine;
|
|
22
|
+
emailSenders;
|
|
23
|
+
logger;
|
|
24
|
+
config;
|
|
25
|
+
webhookHandlers;
|
|
26
|
+
templateCache;
|
|
27
|
+
retryStorage;
|
|
28
|
+
retryMetrics;
|
|
29
|
+
constructor(config) {
|
|
30
|
+
this.config = config;
|
|
31
|
+
this.db = new DatabaseManager(config.database);
|
|
32
|
+
this.logger = new Logger({ level: LogLevel.INFO, transports: [], context: { service: 'email-service' } });
|
|
33
|
+
this.templateEngine = new TemplateEngine({});
|
|
34
|
+
this.emailSenders = new Map();
|
|
35
|
+
this.webhookHandlers = new Map();
|
|
36
|
+
this.templateCache = new Map();
|
|
37
|
+
this.retryStorage = new MemoryRetryStateStorage();
|
|
38
|
+
// Initialize retry metrics if enabled
|
|
39
|
+
if (config.retry?.enableMetrics) {
|
|
40
|
+
this.retryMetrics = new MetricsCollector({
|
|
41
|
+
enabled: true
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
// Initialize providers
|
|
45
|
+
this.initializeProviders(config.providers);
|
|
46
|
+
// Initialize queue if configured
|
|
47
|
+
if (config.queue) {
|
|
48
|
+
this.queue = new QueueManager('email-service', config.queue);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
initializeProviders(providers) {
|
|
52
|
+
for (const providerConfig of providers) {
|
|
53
|
+
try {
|
|
54
|
+
const sender = new EmailSender({
|
|
55
|
+
provider: providerConfig.type,
|
|
56
|
+
apiKey: providerConfig.apiKey,
|
|
57
|
+
domain: providerConfig.domain,
|
|
58
|
+
region: providerConfig.region,
|
|
59
|
+
fromEmail: 'noreply@example.com',
|
|
60
|
+
host: providerConfig.smtp?.host,
|
|
61
|
+
port: providerConfig.smtp?.port,
|
|
62
|
+
secure: providerConfig.smtp?.secure,
|
|
63
|
+
username: providerConfig.smtp?.auth.user,
|
|
64
|
+
password: providerConfig.smtp?.auth.pass
|
|
65
|
+
});
|
|
66
|
+
this.emailSenders.set(providerConfig.type, sender);
|
|
67
|
+
this.logger.info(`Initialized ${providerConfig.type} provider`);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
71
|
+
this.logger.error(`Failed to initialize ${providerConfig.type} provider`, err);
|
|
72
|
+
throw new ProviderError(`Failed to initialize ${providerConfig.type}`, providerConfig.type, { cause: err });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async initialize() {
|
|
77
|
+
try {
|
|
78
|
+
await this.db.connect();
|
|
79
|
+
await this.createTables();
|
|
80
|
+
this.logger.info('Email service initialized successfully');
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
84
|
+
this.logger.error('Failed to initialize email service', err);
|
|
85
|
+
throw new EmailServiceError('Initialization failed', { code: 'INIT_ERROR', cause: err });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async createTables() {
|
|
89
|
+
// Templates table
|
|
90
|
+
await this.db.execute(`
|
|
91
|
+
CREATE TABLE IF NOT EXISTS email_templates (
|
|
92
|
+
id TEXT PRIMARY KEY,
|
|
93
|
+
name TEXT UNIQUE NOT NULL,
|
|
94
|
+
subject TEXT NOT NULL,
|
|
95
|
+
html TEXT NOT NULL,
|
|
96
|
+
text TEXT,
|
|
97
|
+
variables TEXT NOT NULL,
|
|
98
|
+
version INTEGER DEFAULT 1,
|
|
99
|
+
created_at TEXT NOT NULL,
|
|
100
|
+
updated_at TEXT NOT NULL
|
|
101
|
+
)
|
|
102
|
+
`);
|
|
103
|
+
// Delivery records table
|
|
104
|
+
await this.db.execute(`
|
|
105
|
+
CREATE TABLE IF NOT EXISTS email_deliveries (
|
|
106
|
+
id TEXT PRIMARY KEY,
|
|
107
|
+
message_id TEXT NOT NULL,
|
|
108
|
+
to_address TEXT NOT NULL,
|
|
109
|
+
from_address TEXT NOT NULL,
|
|
110
|
+
subject TEXT NOT NULL,
|
|
111
|
+
provider TEXT NOT NULL,
|
|
112
|
+
status TEXT NOT NULL,
|
|
113
|
+
template_id TEXT,
|
|
114
|
+
metadata TEXT,
|
|
115
|
+
sent_at TEXT,
|
|
116
|
+
delivered_at TEXT,
|
|
117
|
+
opened_at TEXT,
|
|
118
|
+
clicked_at TEXT,
|
|
119
|
+
bounced_at TEXT,
|
|
120
|
+
error TEXT,
|
|
121
|
+
created_at TEXT NOT NULL,
|
|
122
|
+
updated_at TEXT NOT NULL
|
|
123
|
+
)
|
|
124
|
+
`);
|
|
125
|
+
// Subscribers table
|
|
126
|
+
await this.db.execute(`
|
|
127
|
+
CREATE TABLE IF NOT EXISTS subscribers (
|
|
128
|
+
id TEXT PRIMARY KEY,
|
|
129
|
+
email TEXT UNIQUE NOT NULL,
|
|
130
|
+
name TEXT,
|
|
131
|
+
status TEXT NOT NULL,
|
|
132
|
+
lists TEXT NOT NULL,
|
|
133
|
+
tags TEXT,
|
|
134
|
+
metadata TEXT,
|
|
135
|
+
subscribed_at TEXT NOT NULL,
|
|
136
|
+
unsubscribed_at TEXT,
|
|
137
|
+
created_at TEXT NOT NULL,
|
|
138
|
+
updated_at TEXT NOT NULL
|
|
139
|
+
)
|
|
140
|
+
`);
|
|
141
|
+
// Subscriber lists table
|
|
142
|
+
await this.db.execute(`
|
|
143
|
+
CREATE TABLE IF NOT EXISTS subscriber_lists (
|
|
144
|
+
id TEXT PRIMARY KEY,
|
|
145
|
+
name TEXT UNIQUE NOT NULL,
|
|
146
|
+
description TEXT,
|
|
147
|
+
subscriber_count INTEGER DEFAULT 0,
|
|
148
|
+
created_at TEXT NOT NULL,
|
|
149
|
+
updated_at TEXT NOT NULL
|
|
150
|
+
)
|
|
151
|
+
`);
|
|
152
|
+
this.logger.info('Database tables created successfully');
|
|
153
|
+
}
|
|
154
|
+
// ===== Email Sending =====
|
|
155
|
+
async send(request) {
|
|
156
|
+
try {
|
|
157
|
+
// Validate email addresses if enabled
|
|
158
|
+
if (this.config.validation?.validateRecipients) {
|
|
159
|
+
const recipients = Array.isArray(request.to) ? request.to : [request.to];
|
|
160
|
+
for (const recipient of recipients) {
|
|
161
|
+
const email = typeof recipient === 'string' ? recipient : recipient.email;
|
|
162
|
+
// Basic email validation
|
|
163
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
164
|
+
if (!emailRegex.test(email)) {
|
|
165
|
+
throw new DeliveryError(`Invalid recipient email: ${email}`, request.provider);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
// Handle scheduled emails
|
|
170
|
+
if (request.scheduledAt && request.scheduledAt > new Date()) {
|
|
171
|
+
return await this.scheduleEmail(request);
|
|
172
|
+
}
|
|
173
|
+
// Process template if specified
|
|
174
|
+
let html = request.html;
|
|
175
|
+
let text = request.text;
|
|
176
|
+
let subject = request.subject;
|
|
177
|
+
if (request.templateId) {
|
|
178
|
+
const rendered = await this.renderTemplate(request.templateId, request.templateData || {});
|
|
179
|
+
html = rendered.html;
|
|
180
|
+
text = rendered.text;
|
|
181
|
+
subject = rendered.subject;
|
|
182
|
+
}
|
|
183
|
+
// Select provider
|
|
184
|
+
const provider = request.provider || this.config.defaultProvider || this.config.providers[0].type;
|
|
185
|
+
const sender = this.emailSenders.get(provider);
|
|
186
|
+
if (!sender) {
|
|
187
|
+
throw new ProviderError(`Provider ${provider} not configured`, provider);
|
|
188
|
+
}
|
|
189
|
+
// Create delivery record
|
|
190
|
+
const deliveryId = this.generateId();
|
|
191
|
+
const deliveryData = {
|
|
192
|
+
id: deliveryId,
|
|
193
|
+
message_id: '',
|
|
194
|
+
to_address: Array.isArray(request.to) ? request.to[0].toString() : request.to,
|
|
195
|
+
from_address: typeof request.from === 'string' ? request.from : request.from.email,
|
|
196
|
+
subject,
|
|
197
|
+
provider,
|
|
198
|
+
status: DeliveryStatus.SENDING,
|
|
199
|
+
template_id: request.templateId || null,
|
|
200
|
+
metadata: request.metadata ? JSON.stringify(request.metadata) : null,
|
|
201
|
+
sent_at: null,
|
|
202
|
+
delivered_at: null,
|
|
203
|
+
opened_at: null,
|
|
204
|
+
clicked_at: null,
|
|
205
|
+
bounced_at: null,
|
|
206
|
+
error: null,
|
|
207
|
+
created_at: new Date().toISOString(),
|
|
208
|
+
updated_at: new Date().toISOString()
|
|
209
|
+
};
|
|
210
|
+
await this.db.insert('email_deliveries', deliveryData);
|
|
211
|
+
// Send email with retry logic
|
|
212
|
+
const toEmail = Array.isArray(request.to)
|
|
213
|
+
? (typeof request.to[0] === 'string' ? request.to[0] : request.to[0].email)
|
|
214
|
+
: request.to;
|
|
215
|
+
const fromEmail = typeof request.from === 'string' ? request.from : request.from.email;
|
|
216
|
+
const fromName = typeof request.from === 'string' ? undefined : request.from.name;
|
|
217
|
+
const emailMessage = {
|
|
218
|
+
toEmail,
|
|
219
|
+
fromEmail,
|
|
220
|
+
fromName,
|
|
221
|
+
subject,
|
|
222
|
+
htmlContent: html,
|
|
223
|
+
textContent: text,
|
|
224
|
+
headers: request.headers,
|
|
225
|
+
metadata: request.metadata
|
|
226
|
+
};
|
|
227
|
+
// Use retry logic if configured
|
|
228
|
+
const result = await this.sendWithRetry(sender, emailMessage, deliveryId, provider);
|
|
229
|
+
// Update delivery record
|
|
230
|
+
await this.db.update('email_deliveries', deliveryId, {
|
|
231
|
+
message_id: result.messageId || '',
|
|
232
|
+
status: result.success ? DeliveryStatus.SENT : DeliveryStatus.FAILED,
|
|
233
|
+
sent_at: result.success ? new Date().toISOString() : null,
|
|
234
|
+
error: result.errorMessage || null,
|
|
235
|
+
updated_at: new Date().toISOString()
|
|
236
|
+
});
|
|
237
|
+
this.logger.info(`Email sent via ${provider}`, { deliveryId, messageId: result.messageId });
|
|
238
|
+
return {
|
|
239
|
+
success: result.success,
|
|
240
|
+
messageId: result.messageId,
|
|
241
|
+
deliveryId,
|
|
242
|
+
provider,
|
|
243
|
+
error: result.errorMessage,
|
|
244
|
+
timestamp: new Date()
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
249
|
+
this.logger.error('Failed to send email', err);
|
|
250
|
+
throw new DeliveryError(err.message, request.provider, { cause: err });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async scheduleEmail(request) {
|
|
254
|
+
if (!this.queue) {
|
|
255
|
+
throw new EmailServiceError('Queue not configured for scheduled emails', { code: 'QUEUE_NOT_CONFIGURED' });
|
|
256
|
+
}
|
|
257
|
+
const delay = request.scheduledAt.getTime() - Date.now();
|
|
258
|
+
const priority = request.priority === 'high' ? JobPriority.HIGH :
|
|
259
|
+
request.priority === 'low' ? JobPriority.LOW :
|
|
260
|
+
JobPriority.NORMAL;
|
|
261
|
+
await this.queue.add('send-email', request, {
|
|
262
|
+
priority,
|
|
263
|
+
delay
|
|
264
|
+
});
|
|
265
|
+
this.logger.info('Email scheduled for delivery', { scheduledAt: request.scheduledAt });
|
|
266
|
+
return {
|
|
267
|
+
success: true,
|
|
268
|
+
queuedForLater: true,
|
|
269
|
+
timestamp: new Date()
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
async sendBulk(requests) {
|
|
273
|
+
const results = [];
|
|
274
|
+
for (const request of requests) {
|
|
275
|
+
try {
|
|
276
|
+
const result = await this.send(request);
|
|
277
|
+
results.push(result);
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
results.push({
|
|
281
|
+
success: false,
|
|
282
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
283
|
+
timestamp: new Date()
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return results;
|
|
288
|
+
}
|
|
289
|
+
// ===== Template Management =====
|
|
290
|
+
async createTemplate(request) {
|
|
291
|
+
try {
|
|
292
|
+
const id = this.generateId();
|
|
293
|
+
const now = new Date();
|
|
294
|
+
// Extract variables from all template parts
|
|
295
|
+
const allContent = [request.subject, request.html, request.text].filter(Boolean).join(' ');
|
|
296
|
+
const variables = this.extractVariables(allContent);
|
|
297
|
+
const template = {
|
|
298
|
+
id,
|
|
299
|
+
name: request.name,
|
|
300
|
+
subject: request.subject,
|
|
301
|
+
html: request.html,
|
|
302
|
+
text: request.text,
|
|
303
|
+
variables,
|
|
304
|
+
version: 1,
|
|
305
|
+
createdAt: now,
|
|
306
|
+
updatedAt: now
|
|
307
|
+
};
|
|
308
|
+
await this.db.insert('email_templates', {
|
|
309
|
+
id,
|
|
310
|
+
name: request.name,
|
|
311
|
+
subject: request.subject,
|
|
312
|
+
html: request.html,
|
|
313
|
+
text: request.text || null,
|
|
314
|
+
variables: JSON.stringify(variables),
|
|
315
|
+
version: 1,
|
|
316
|
+
created_at: now.toISOString(),
|
|
317
|
+
updated_at: now.toISOString()
|
|
318
|
+
});
|
|
319
|
+
if (this.config.templates?.cacheEnabled) {
|
|
320
|
+
this.templateCache.set(id, template);
|
|
321
|
+
}
|
|
322
|
+
this.logger.info(`Template created: ${request.name}`, { id });
|
|
323
|
+
return template;
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
327
|
+
this.logger.error('Failed to create template', err);
|
|
328
|
+
throw new TemplateError(err.message, { cause: err });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
async getTemplate(id) {
|
|
332
|
+
// Check cache first
|
|
333
|
+
if (this.config.templates?.cacheEnabled && this.templateCache.has(id)) {
|
|
334
|
+
return this.templateCache.get(id);
|
|
335
|
+
}
|
|
336
|
+
const template = await this.db.findById('email_templates', id);
|
|
337
|
+
if (!template) {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
const parsed = {
|
|
341
|
+
...template,
|
|
342
|
+
variables: JSON.parse(template.variables),
|
|
343
|
+
createdAt: new Date(template.created_at),
|
|
344
|
+
updatedAt: new Date(template.updated_at)
|
|
345
|
+
};
|
|
346
|
+
if (this.config.templates?.cacheEnabled) {
|
|
347
|
+
this.templateCache.set(id, parsed);
|
|
348
|
+
}
|
|
349
|
+
return parsed;
|
|
350
|
+
}
|
|
351
|
+
async updateTemplate(id, update) {
|
|
352
|
+
const existing = await this.getTemplate(id);
|
|
353
|
+
if (!existing) {
|
|
354
|
+
throw new TemplateError(`Template ${id} not found`);
|
|
355
|
+
}
|
|
356
|
+
const html = update.html || existing.html;
|
|
357
|
+
const subject = update.subject || existing.subject;
|
|
358
|
+
const text = update.text || existing.text;
|
|
359
|
+
const allContent = [subject, html, text].filter(Boolean).join(' ');
|
|
360
|
+
const variables = this.extractVariables(allContent);
|
|
361
|
+
const updated = await this.db.update('email_templates', id, {
|
|
362
|
+
subject: update.subject || existing.subject,
|
|
363
|
+
html,
|
|
364
|
+
text: update.text || existing.text,
|
|
365
|
+
variables: JSON.stringify(variables),
|
|
366
|
+
version: existing.version + 1,
|
|
367
|
+
updated_at: new Date().toISOString()
|
|
368
|
+
});
|
|
369
|
+
// Invalidate cache
|
|
370
|
+
this.templateCache.delete(id);
|
|
371
|
+
const result = {
|
|
372
|
+
id: updated.id,
|
|
373
|
+
name: updated.name,
|
|
374
|
+
subject: updated.subject,
|
|
375
|
+
html: updated.html,
|
|
376
|
+
text: updated.text,
|
|
377
|
+
variables: JSON.parse(updated.variables),
|
|
378
|
+
version: updated.version,
|
|
379
|
+
createdAt: new Date(updated.created_at),
|
|
380
|
+
updatedAt: new Date(updated.updated_at)
|
|
381
|
+
};
|
|
382
|
+
return result;
|
|
383
|
+
}
|
|
384
|
+
async deleteTemplate(id) {
|
|
385
|
+
const deleted = await this.db.delete('email_templates', id);
|
|
386
|
+
this.templateCache.delete(id);
|
|
387
|
+
return deleted;
|
|
388
|
+
}
|
|
389
|
+
async renderTemplate(templateId, data) {
|
|
390
|
+
const template = await this.getTemplate(templateId);
|
|
391
|
+
if (!template) {
|
|
392
|
+
throw new TemplateError(`Template ${templateId} not found`);
|
|
393
|
+
}
|
|
394
|
+
const html = await this.templateEngine.render(template.html, data);
|
|
395
|
+
const text = template.text ? await this.templateEngine.render(template.text, data) : undefined;
|
|
396
|
+
const subject = await this.templateEngine.render(template.subject, data);
|
|
397
|
+
return { html, text, subject };
|
|
398
|
+
}
|
|
399
|
+
extractVariables(template) {
|
|
400
|
+
const regex = /\{\{([^}]+)\}\}/g;
|
|
401
|
+
const variables = new Set();
|
|
402
|
+
let match;
|
|
403
|
+
while ((match = regex.exec(template)) !== null) {
|
|
404
|
+
variables.add(match[1].trim());
|
|
405
|
+
}
|
|
406
|
+
return Array.from(variables);
|
|
407
|
+
}
|
|
408
|
+
// ===== Delivery Tracking =====
|
|
409
|
+
async getDelivery(id) {
|
|
410
|
+
const record = await this.db.findById('email_deliveries', id);
|
|
411
|
+
if (!record) {
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
return this.parseDeliveryRecord(record);
|
|
415
|
+
}
|
|
416
|
+
async trackOpen(deliveryId) {
|
|
417
|
+
await this.db.update('email_deliveries', deliveryId, {
|
|
418
|
+
status: DeliveryStatus.OPENED,
|
|
419
|
+
opened_at: new Date().toISOString(),
|
|
420
|
+
updated_at: new Date().toISOString()
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
async trackClick(deliveryId) {
|
|
424
|
+
await this.db.update('email_deliveries', deliveryId, {
|
|
425
|
+
status: DeliveryStatus.CLICKED,
|
|
426
|
+
clicked_at: new Date().toISOString(),
|
|
427
|
+
updated_at: new Date().toISOString()
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
async getDeliveryStats(startDate, endDate) {
|
|
431
|
+
const records = await this.db.findMany('email_deliveries');
|
|
432
|
+
let filtered = records;
|
|
433
|
+
if (startDate || endDate) {
|
|
434
|
+
filtered = records.filter(r => {
|
|
435
|
+
const date = new Date(r.created_at);
|
|
436
|
+
if (startDate && date < startDate)
|
|
437
|
+
return false;
|
|
438
|
+
if (endDate && date > endDate)
|
|
439
|
+
return false;
|
|
440
|
+
return true;
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
const total = filtered.length;
|
|
444
|
+
const sent = filtered.filter(r => r.status !== DeliveryStatus.QUEUED && r.status !== DeliveryStatus.SENDING).length;
|
|
445
|
+
const delivered = filtered.filter(r => r.status === DeliveryStatus.DELIVERED).length;
|
|
446
|
+
const opened = filtered.filter(r => r.opened_at).length;
|
|
447
|
+
const clicked = filtered.filter(r => r.clicked_at).length;
|
|
448
|
+
const bounced = filtered.filter(r => r.status === DeliveryStatus.BOUNCED).length;
|
|
449
|
+
const failed = filtered.filter(r => r.status === DeliveryStatus.FAILED).length;
|
|
450
|
+
return {
|
|
451
|
+
total,
|
|
452
|
+
sent,
|
|
453
|
+
delivered,
|
|
454
|
+
opened,
|
|
455
|
+
clicked,
|
|
456
|
+
bounced,
|
|
457
|
+
failed,
|
|
458
|
+
openRate: sent > 0 ? (opened / sent) * 100 : 0,
|
|
459
|
+
clickRate: sent > 0 ? (clicked / sent) * 100 : 0,
|
|
460
|
+
bounceRate: sent > 0 ? (bounced / sent) * 100 : 0
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
parseDeliveryRecord(record) {
|
|
464
|
+
return {
|
|
465
|
+
...record,
|
|
466
|
+
metadata: record.metadata ? JSON.parse(record.metadata) : undefined,
|
|
467
|
+
createdAt: new Date(record.created_at),
|
|
468
|
+
updatedAt: new Date(record.updated_at),
|
|
469
|
+
sentAt: record.sent_at ? new Date(record.sent_at) : undefined,
|
|
470
|
+
deliveredAt: record.delivered_at ? new Date(record.delivered_at) : undefined,
|
|
471
|
+
openedAt: record.opened_at ? new Date(record.opened_at) : undefined,
|
|
472
|
+
clickedAt: record.clicked_at ? new Date(record.clicked_at) : undefined,
|
|
473
|
+
bouncedAt: record.bounced_at ? new Date(record.bounced_at) : undefined
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
// ===== Subscriber Management =====
|
|
477
|
+
async createSubscriber(request) {
|
|
478
|
+
const id = this.generateId();
|
|
479
|
+
const now = new Date();
|
|
480
|
+
const subscriber = await this.db.insert('subscribers', {
|
|
481
|
+
id,
|
|
482
|
+
email: request.email,
|
|
483
|
+
name: request.name,
|
|
484
|
+
status: 'active',
|
|
485
|
+
lists: JSON.stringify(request.lists || []),
|
|
486
|
+
tags: request.tags ? JSON.stringify(request.tags) : null,
|
|
487
|
+
metadata: request.metadata ? JSON.stringify(request.metadata) : null,
|
|
488
|
+
subscribed_at: now.toISOString(),
|
|
489
|
+
created_at: now.toISOString(),
|
|
490
|
+
updated_at: now.toISOString()
|
|
491
|
+
});
|
|
492
|
+
this.logger.info(`Subscriber created: ${request.email}`, { id });
|
|
493
|
+
return this.parseSubscriber(subscriber);
|
|
494
|
+
}
|
|
495
|
+
async getSubscriber(id) {
|
|
496
|
+
const subscriber = await this.db.findById('subscribers', id);
|
|
497
|
+
return subscriber ? this.parseSubscriber(subscriber) : null;
|
|
498
|
+
}
|
|
499
|
+
async updateSubscriber(id, update) {
|
|
500
|
+
const updateData = {
|
|
501
|
+
updated_at: new Date().toISOString()
|
|
502
|
+
};
|
|
503
|
+
if (update.name !== undefined)
|
|
504
|
+
updateData.name = update.name;
|
|
505
|
+
if (update.status !== undefined)
|
|
506
|
+
updateData.status = update.status;
|
|
507
|
+
if (update.lists !== undefined)
|
|
508
|
+
updateData.lists = JSON.stringify(update.lists);
|
|
509
|
+
if (update.tags !== undefined)
|
|
510
|
+
updateData.tags = JSON.stringify(update.tags);
|
|
511
|
+
if (update.metadata !== undefined)
|
|
512
|
+
updateData.metadata = JSON.stringify(update.metadata);
|
|
513
|
+
const updated = await this.db.update('subscribers', id, updateData);
|
|
514
|
+
return this.parseSubscriber(updated);
|
|
515
|
+
}
|
|
516
|
+
async unsubscribe(email) {
|
|
517
|
+
const subscriber = await this.db.findOne('subscribers', { email });
|
|
518
|
+
if (!subscriber) {
|
|
519
|
+
return false;
|
|
520
|
+
}
|
|
521
|
+
await this.db.update('subscribers', subscriber.id, {
|
|
522
|
+
status: 'unsubscribed',
|
|
523
|
+
unsubscribed_at: new Date().toISOString(),
|
|
524
|
+
updated_at: new Date().toISOString()
|
|
525
|
+
});
|
|
526
|
+
this.logger.info(`Subscriber unsubscribed: ${email}`);
|
|
527
|
+
return true;
|
|
528
|
+
}
|
|
529
|
+
parseSubscriber(record) {
|
|
530
|
+
return {
|
|
531
|
+
...record,
|
|
532
|
+
lists: JSON.parse(record.lists),
|
|
533
|
+
tags: record.tags ? JSON.parse(record.tags) : undefined,
|
|
534
|
+
metadata: record.metadata ? JSON.parse(record.metadata) : undefined,
|
|
535
|
+
subscribedAt: new Date(record.subscribed_at || record.subscribedAt),
|
|
536
|
+
unsubscribedAt: record.unsubscribed_at ? new Date(record.unsubscribed_at) : undefined,
|
|
537
|
+
createdAt: new Date(record.created_at || record.createdAt),
|
|
538
|
+
updatedAt: new Date(record.updated_at || record.updatedAt)
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
async createList(name, description) {
|
|
542
|
+
const id = this.generateId();
|
|
543
|
+
const now = new Date();
|
|
544
|
+
const record = await this.db.insert('subscriber_lists', {
|
|
545
|
+
id,
|
|
546
|
+
name,
|
|
547
|
+
description,
|
|
548
|
+
subscriber_count: 0,
|
|
549
|
+
created_at: now.toISOString(),
|
|
550
|
+
updated_at: now.toISOString()
|
|
551
|
+
});
|
|
552
|
+
return {
|
|
553
|
+
id: record.id,
|
|
554
|
+
name: record.name,
|
|
555
|
+
description: record.description,
|
|
556
|
+
subscriberCount: record.subscriber_count,
|
|
557
|
+
createdAt: new Date(record.created_at),
|
|
558
|
+
updatedAt: new Date(record.updated_at)
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
// ===== Webhooks =====
|
|
562
|
+
registerWebhookHandler(event, handler) {
|
|
563
|
+
if (!this.webhookHandlers.has(event)) {
|
|
564
|
+
this.webhookHandlers.set(event, []);
|
|
565
|
+
}
|
|
566
|
+
this.webhookHandlers.get(event).push(handler);
|
|
567
|
+
}
|
|
568
|
+
async handleWebhook(event) {
|
|
569
|
+
const handlers = this.webhookHandlers.get(event.event) || [];
|
|
570
|
+
for (const handler of handlers) {
|
|
571
|
+
try {
|
|
572
|
+
await handler(event);
|
|
573
|
+
}
|
|
574
|
+
catch (error) {
|
|
575
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
576
|
+
this.logger.error(`Webhook handler error for ${event.event}`, err);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
// ===== Lifecycle =====
|
|
581
|
+
async shutdown() {
|
|
582
|
+
if (this.queue) {
|
|
583
|
+
await this.queue.close();
|
|
584
|
+
}
|
|
585
|
+
await this.db.disconnect();
|
|
586
|
+
this.logger.info('Email service shutdown complete');
|
|
587
|
+
}
|
|
588
|
+
generateId() {
|
|
589
|
+
return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
|
|
590
|
+
}
|
|
591
|
+
// ===== Magic Link Support =====
|
|
592
|
+
async sendMagicLink(config) {
|
|
593
|
+
try {
|
|
594
|
+
if (!this.config.magicLink?.secret) {
|
|
595
|
+
throw new EmailServiceError('Magic link configuration is missing. Please provide magicLink.secret in EmailServiceConfig', { code: 'MAGIC_LINK_NOT_CONFIGURED' });
|
|
596
|
+
}
|
|
597
|
+
// Generate secure token
|
|
598
|
+
const expirationMinutes = config.expirationMinutes || this.config.magicLink.expirationMinutes || 60;
|
|
599
|
+
const expiresAt = new Date(Date.now() + expirationMinutes * 60 * 1000);
|
|
600
|
+
const tokenPayload = {
|
|
601
|
+
email: config.recipient,
|
|
602
|
+
purpose: config.purpose,
|
|
603
|
+
customData: config.customData
|
|
604
|
+
};
|
|
605
|
+
// Create signed token using crypto-utils (JWT)
|
|
606
|
+
const token = generateJWT(tokenPayload, this.config.magicLink.secret, {
|
|
607
|
+
algorithm: 'HS256',
|
|
608
|
+
expiresIn: expirationMinutes * 60, // seconds
|
|
609
|
+
issuer: this.config.magicLink.issuer || 'email-service',
|
|
610
|
+
includeIssuedAt: true
|
|
611
|
+
});
|
|
612
|
+
// Build magic link
|
|
613
|
+
const magicLink = `${config.redirectUrl}${config.redirectUrl.includes('?') ? '&' : '?'}token=${token}`;
|
|
614
|
+
// Prepare email content
|
|
615
|
+
const subject = config.subject || `Your ${config.purpose} link`;
|
|
616
|
+
let html;
|
|
617
|
+
let text;
|
|
618
|
+
if (config.template && config.templateData) {
|
|
619
|
+
// Use custom template
|
|
620
|
+
const rendered = await this.renderTemplate(config.template, {
|
|
621
|
+
...config.templateData,
|
|
622
|
+
magicLink,
|
|
623
|
+
purpose: config.purpose,
|
|
624
|
+
expiresAt: expiresAt.toISOString(),
|
|
625
|
+
expirationMinutes
|
|
626
|
+
});
|
|
627
|
+
html = rendered.html;
|
|
628
|
+
text = rendered.text || this.createDefaultMagicLinkText(magicLink, config.purpose, expirationMinutes);
|
|
629
|
+
}
|
|
630
|
+
else {
|
|
631
|
+
// Use default template
|
|
632
|
+
html = this.createDefaultMagicLinkHtml(magicLink, config.purpose, expirationMinutes);
|
|
633
|
+
text = this.createDefaultMagicLinkText(magicLink, config.purpose, expirationMinutes);
|
|
634
|
+
}
|
|
635
|
+
// Send email
|
|
636
|
+
const emailRequest = {
|
|
637
|
+
from: config.fromEmail || 'noreply@example.com',
|
|
638
|
+
to: [config.recipient],
|
|
639
|
+
subject,
|
|
640
|
+
html,
|
|
641
|
+
text,
|
|
642
|
+
provider: config.provider,
|
|
643
|
+
metadata: {
|
|
644
|
+
type: 'magic-link',
|
|
645
|
+
purpose: config.purpose,
|
|
646
|
+
...config.customData
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
let emailResult;
|
|
650
|
+
try {
|
|
651
|
+
emailResult = await this.send(emailRequest);
|
|
652
|
+
}
|
|
653
|
+
catch (sendError) {
|
|
654
|
+
const sendErr = sendError instanceof Error ? sendError : new Error(String(sendError));
|
|
655
|
+
this.logger.error('Failed to send magic link email', sendErr);
|
|
656
|
+
return {
|
|
657
|
+
success: false,
|
|
658
|
+
magicLink,
|
|
659
|
+
token,
|
|
660
|
+
expiresAt,
|
|
661
|
+
error: sendErr.message
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
this.logger.info(`Magic link email sent`, {
|
|
665
|
+
recipient: config.recipient,
|
|
666
|
+
purpose: config.purpose,
|
|
667
|
+
expiresAt
|
|
668
|
+
});
|
|
669
|
+
return {
|
|
670
|
+
success: emailResult.success,
|
|
671
|
+
magicLink,
|
|
672
|
+
token,
|
|
673
|
+
expiresAt,
|
|
674
|
+
error: emailResult.error,
|
|
675
|
+
emailResult
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
catch (error) {
|
|
679
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
680
|
+
this.logger.error('Failed to generate magic link', err);
|
|
681
|
+
return {
|
|
682
|
+
success: false,
|
|
683
|
+
error: err.message
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
createDefaultMagicLinkHtml(link, purpose, expirationMinutes) {
|
|
688
|
+
return `
|
|
689
|
+
<!DOCTYPE html>
|
|
690
|
+
<html>
|
|
691
|
+
<head>
|
|
692
|
+
<meta charset="utf-8">
|
|
693
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
694
|
+
</head>
|
|
695
|
+
<body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
|
|
696
|
+
<h2 style="color: #333;">Your Magic Link</h2>
|
|
697
|
+
<p style="color: #666; line-height: 1.6;">
|
|
698
|
+
Click the button below to ${purpose}:
|
|
699
|
+
</p>
|
|
700
|
+
<div style="margin: 30px 0;">
|
|
701
|
+
<a href="${link}"
|
|
702
|
+
style="background-color: #007bff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;">
|
|
703
|
+
Continue
|
|
704
|
+
</a>
|
|
705
|
+
</div>
|
|
706
|
+
<p style="color: #666; font-size: 14px; line-height: 1.6;">
|
|
707
|
+
If the button doesn't work, copy and paste this link into your browser:
|
|
708
|
+
</p>
|
|
709
|
+
<p style="background-color: #f5f5f5; padding: 10px; border-radius: 4px; word-break: break-all; font-family: monospace; font-size: 12px;">
|
|
710
|
+
${link}
|
|
711
|
+
</p>
|
|
712
|
+
<p style="color: #999; font-size: 12px; margin-top: 30px;">
|
|
713
|
+
This link will expire in ${expirationMinutes} minutes for security reasons.
|
|
714
|
+
</p>
|
|
715
|
+
</body>
|
|
716
|
+
</html>
|
|
717
|
+
`;
|
|
718
|
+
}
|
|
719
|
+
createDefaultMagicLinkText(link, purpose, expirationMinutes) {
|
|
720
|
+
return `
|
|
721
|
+
Your Magic Link
|
|
722
|
+
|
|
723
|
+
Click the link below to ${purpose}:
|
|
724
|
+
${link}
|
|
725
|
+
|
|
726
|
+
This link will expire in ${expirationMinutes} minutes for security reasons.
|
|
727
|
+
|
|
728
|
+
If you did not request this link, please ignore this email.
|
|
729
|
+
`.trim();
|
|
730
|
+
}
|
|
731
|
+
// ===== Retry Integration =====
|
|
732
|
+
async sendWithRetry(sender, message, deliveryId, provider) {
|
|
733
|
+
const maxRetries = this.config.retry?.maxRetries || 0;
|
|
734
|
+
// If retry is not configured, send directly
|
|
735
|
+
if (maxRetries === 0) {
|
|
736
|
+
return await sender.sendEmail(message);
|
|
737
|
+
}
|
|
738
|
+
// Create retry state
|
|
739
|
+
const retryState = createRetryState({
|
|
740
|
+
id: deliveryId,
|
|
741
|
+
maxRetries,
|
|
742
|
+
initialDelayMs: this.config.retry?.initialDelayMs || 1000
|
|
743
|
+
});
|
|
744
|
+
await this.retryStorage.set(deliveryId, retryState);
|
|
745
|
+
let attempt = 0;
|
|
746
|
+
let lastError = null;
|
|
747
|
+
while (attempt <= maxRetries) {
|
|
748
|
+
const startTime = Date.now();
|
|
749
|
+
try {
|
|
750
|
+
// Record attempt start
|
|
751
|
+
if (this.retryMetrics) {
|
|
752
|
+
this.retryMetrics.recordAttemptStart(deliveryId, attempt);
|
|
753
|
+
}
|
|
754
|
+
const result = await sender.sendEmail(message);
|
|
755
|
+
const duration = Date.now() - startTime;
|
|
756
|
+
// Record success metric
|
|
757
|
+
if (this.retryMetrics) {
|
|
758
|
+
this.retryMetrics.recordAttemptEnd(deliveryId, attempt, true, duration);
|
|
759
|
+
}
|
|
760
|
+
// Update retry state
|
|
761
|
+
await this.retryStorage.set(deliveryId, {
|
|
762
|
+
...retryState,
|
|
763
|
+
status: 'completed',
|
|
764
|
+
attempt,
|
|
765
|
+
lastAttempt: new Date()
|
|
766
|
+
});
|
|
767
|
+
this.logger.info(`Email sent successfully`, {
|
|
768
|
+
deliveryId,
|
|
769
|
+
provider,
|
|
770
|
+
attempt,
|
|
771
|
+
duration
|
|
772
|
+
});
|
|
773
|
+
return result;
|
|
774
|
+
}
|
|
775
|
+
catch (error) {
|
|
776
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
777
|
+
const duration = Date.now() - startTime;
|
|
778
|
+
// Record failure metric
|
|
779
|
+
if (this.retryMetrics) {
|
|
780
|
+
this.retryMetrics.recordAttemptEnd(deliveryId, attempt, false, duration, lastError.message);
|
|
781
|
+
}
|
|
782
|
+
// Check if we should retry
|
|
783
|
+
if (attempt < maxRetries && shouldRetry(attempt, lastError, { maxRetries })) {
|
|
784
|
+
// Calculate delay
|
|
785
|
+
const delay = calculateRetryDelay(attempt, {
|
|
786
|
+
initialDelayMs: this.config.retry?.initialDelayMs || 1000,
|
|
787
|
+
maxDelayMs: this.config.retry?.maxDelayMs || 30000,
|
|
788
|
+
jitter: this.config.retry?.jitter ?? true
|
|
789
|
+
});
|
|
790
|
+
// Update retry state
|
|
791
|
+
await this.retryStorage.set(deliveryId, {
|
|
792
|
+
...retryState,
|
|
793
|
+
status: 'retrying',
|
|
794
|
+
attempt,
|
|
795
|
+
lastAttempt: new Date(),
|
|
796
|
+
error: lastError
|
|
797
|
+
});
|
|
798
|
+
this.logger.warn(`Email send failed, retrying in ${delay}ms`, {
|
|
799
|
+
deliveryId,
|
|
800
|
+
provider,
|
|
801
|
+
attempt: attempt + 1,
|
|
802
|
+
maxRetries,
|
|
803
|
+
error: lastError.message
|
|
804
|
+
});
|
|
805
|
+
// Wait before retrying
|
|
806
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
807
|
+
attempt++;
|
|
808
|
+
}
|
|
809
|
+
else {
|
|
810
|
+
break;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
// All retries exhausted - final failure recorded above
|
|
815
|
+
await this.retryStorage.set(deliveryId, {
|
|
816
|
+
...retryState,
|
|
817
|
+
status: 'failed',
|
|
818
|
+
attempt,
|
|
819
|
+
lastAttempt: new Date(),
|
|
820
|
+
error: lastError || new Error('Unknown error')
|
|
821
|
+
});
|
|
822
|
+
this.logger.error(`Email send failed after ${attempt} attempts`, lastError || undefined, {
|
|
823
|
+
deliveryId,
|
|
824
|
+
provider
|
|
825
|
+
});
|
|
826
|
+
// Return failure result matching EmailSender result shape
|
|
827
|
+
return {
|
|
828
|
+
success: false,
|
|
829
|
+
messageId: undefined,
|
|
830
|
+
errorMessage: lastError?.message || 'Failed to send email after retries'
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { EmailProvider } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Typed error code union for email-service errors.
|
|
4
|
+
*/
|
|
5
|
+
export type EmailServiceErrorCode = 'EMAIL_SERVICE_ERROR' | 'PROVIDER_ERROR' | 'TEMPLATE_ERROR' | 'DELIVERY_ERROR' | 'INIT_ERROR' | 'QUEUE_NOT_CONFIGURED' | 'MAGIC_LINK_NOT_CONFIGURED' | string;
|
|
6
|
+
/**
|
|
7
|
+
* Options bag accepted by all email-service error classes.
|
|
8
|
+
*
|
|
9
|
+
* - `cause`: chained underlying error (ES2022 Error.cause).
|
|
10
|
+
* - `code`: a typed error code from {@link EmailServiceErrorCode}.
|
|
11
|
+
* - `context`: arbitrary structured context — provider/templateId/etc.
|
|
12
|
+
*/
|
|
13
|
+
export interface EmailServiceErrorOptions {
|
|
14
|
+
cause?: Error;
|
|
15
|
+
code?: EmailServiceErrorCode;
|
|
16
|
+
context?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Base error class for email-service.
|
|
20
|
+
*
|
|
21
|
+
* Uses native ES2022 `Error.cause` for error chaining — read the underlying
|
|
22
|
+
* error via `error.cause`. Subclass-specific fields (e.g. `provider`) live on
|
|
23
|
+
* `error.context` since 5.0.0 — read via `error.context?.provider`.
|
|
24
|
+
*/
|
|
25
|
+
export declare class EmailServiceError extends Error {
|
|
26
|
+
readonly code: EmailServiceErrorCode;
|
|
27
|
+
readonly context?: Record<string, unknown>;
|
|
28
|
+
constructor(message: string, options?: EmailServiceErrorOptions);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Provider-specific error.
|
|
32
|
+
*
|
|
33
|
+
* Convenience constructor accepts `provider`; stored on `context.provider`.
|
|
34
|
+
*/
|
|
35
|
+
export declare class ProviderError extends EmailServiceError {
|
|
36
|
+
constructor(message: string, provider: EmailProvider, options?: Omit<EmailServiceErrorOptions, 'code'>);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Template-related error.
|
|
40
|
+
*/
|
|
41
|
+
export declare class TemplateError extends EmailServiceError {
|
|
42
|
+
constructor(message: string, options?: Omit<EmailServiceErrorOptions, 'code'>);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Delivery-related error.
|
|
46
|
+
*
|
|
47
|
+
* Convenience constructor accepts an optional `provider`; stored on
|
|
48
|
+
* `context.provider` when present.
|
|
49
|
+
*/
|
|
50
|
+
export declare class DeliveryError extends EmailServiceError {
|
|
51
|
+
constructor(message: string, provider?: EmailProvider, options?: Omit<EmailServiceErrorOptions, 'code'>);
|
|
52
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright (c) 2025 Bernier LLC
|
|
3
|
+
|
|
4
|
+
This file is licensed to the client under a limited-use license.
|
|
5
|
+
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
+
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Base error class for email-service.
|
|
10
|
+
*
|
|
11
|
+
* Uses native ES2022 `Error.cause` for error chaining — read the underlying
|
|
12
|
+
* error via `error.cause`. Subclass-specific fields (e.g. `provider`) live on
|
|
13
|
+
* `error.context` since 5.0.0 — read via `error.context?.provider`.
|
|
14
|
+
*/
|
|
15
|
+
export class EmailServiceError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
context;
|
|
18
|
+
constructor(message, options) {
|
|
19
|
+
super(message, options?.cause ? { cause: options.cause } : undefined);
|
|
20
|
+
this.name = 'EmailServiceError';
|
|
21
|
+
this.code = options?.code ?? 'EMAIL_SERVICE_ERROR';
|
|
22
|
+
if (options?.context !== undefined) {
|
|
23
|
+
this.context = options.context;
|
|
24
|
+
}
|
|
25
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Provider-specific error.
|
|
30
|
+
*
|
|
31
|
+
* Convenience constructor accepts `provider`; stored on `context.provider`.
|
|
32
|
+
*/
|
|
33
|
+
export class ProviderError extends EmailServiceError {
|
|
34
|
+
constructor(message, provider, options) {
|
|
35
|
+
super(message, {
|
|
36
|
+
...options,
|
|
37
|
+
code: 'PROVIDER_ERROR',
|
|
38
|
+
context: { ...(options?.context ?? {}), provider },
|
|
39
|
+
});
|
|
40
|
+
this.name = 'ProviderError';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Template-related error.
|
|
45
|
+
*/
|
|
46
|
+
export class TemplateError extends EmailServiceError {
|
|
47
|
+
constructor(message, options) {
|
|
48
|
+
super(message, {
|
|
49
|
+
...options,
|
|
50
|
+
code: 'TEMPLATE_ERROR',
|
|
51
|
+
});
|
|
52
|
+
this.name = 'TemplateError';
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Delivery-related error.
|
|
57
|
+
*
|
|
58
|
+
* Convenience constructor accepts an optional `provider`; stored on
|
|
59
|
+
* `context.provider` when present.
|
|
60
|
+
*/
|
|
61
|
+
export class DeliveryError extends EmailServiceError {
|
|
62
|
+
constructor(message, provider, options) {
|
|
63
|
+
super(message, {
|
|
64
|
+
...options,
|
|
65
|
+
code: 'DELIVERY_ERROR',
|
|
66
|
+
context: provider !== undefined
|
|
67
|
+
? { ...(options?.context ?? {}), provider }
|
|
68
|
+
: options?.context,
|
|
69
|
+
});
|
|
70
|
+
this.name = 'DeliveryError';
|
|
71
|
+
}
|
|
72
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { EmailService } from './email-service.js';
|
|
2
|
+
export type { EmailProvider, ProviderConfig, SMTPConfig, RateLimitConfig, EmailServiceConfig, EmailAddress, EmailAttachment, EmailRequest, EmailResult, SendEmailResult, EmailTemplate, TemplateCreateRequest, TemplateUpdateRequest, DeliveryRecord, DeliveryEvent, DeliveryStats, Subscriber, SubscriberCreateRequest, SubscriberUpdateRequest, SubscriberList, WebhookEvent, WebhookHandler, MagicLinkEmail, MagicLinkResult } from './types.js';
|
|
3
|
+
export { DeliveryStatus, SubscriberStatus, } from './types.js';
|
|
4
|
+
export { EmailServiceError, ProviderError, TemplateError, DeliveryError, } from './errors.js';
|
|
5
|
+
export type { EmailServiceErrorCode, EmailServiceErrorOptions, } from './errors.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright (c) 2025 Bernier LLC
|
|
3
|
+
|
|
4
|
+
This file is licensed to the client under a limited-use license.
|
|
5
|
+
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
+
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
+
*/
|
|
8
|
+
export { EmailService } from './email-service.js';
|
|
9
|
+
export { DeliveryStatus, SubscriberStatus, } from './types.js';
|
|
10
|
+
export { EmailServiceError, ProviderError, TemplateError, DeliveryError, } from './errors.js';
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import type { DatabaseConfig } from '@bernierllc/database-adapter';
|
|
2
|
+
import type { QueueOptions } from '@bernierllc/queue-manager';
|
|
3
|
+
import type { TemplateContext } from '@bernierllc/template-engine';
|
|
4
|
+
export type EmailProvider = 'sendgrid' | 'mailgun' | 'ses' | 'smtp' | 'postmark' | 'mandrill' | 'smtp2go';
|
|
5
|
+
export interface ProviderConfig {
|
|
6
|
+
type: EmailProvider;
|
|
7
|
+
apiKey?: string;
|
|
8
|
+
domain?: string;
|
|
9
|
+
region?: string;
|
|
10
|
+
smtp?: SMTPConfig;
|
|
11
|
+
rateLimit?: RateLimitConfig;
|
|
12
|
+
}
|
|
13
|
+
export interface SMTPConfig {
|
|
14
|
+
host: string;
|
|
15
|
+
port: number;
|
|
16
|
+
secure: boolean;
|
|
17
|
+
auth: {
|
|
18
|
+
user: string;
|
|
19
|
+
pass: string;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export interface RateLimitConfig {
|
|
23
|
+
maxPerSecond: number;
|
|
24
|
+
maxPerMinute: number;
|
|
25
|
+
maxPerHour: number;
|
|
26
|
+
}
|
|
27
|
+
export interface EmailServiceConfig {
|
|
28
|
+
providers: ProviderConfig[];
|
|
29
|
+
defaultProvider?: EmailProvider;
|
|
30
|
+
database: DatabaseConfig;
|
|
31
|
+
queue?: QueueOptions;
|
|
32
|
+
templates?: {
|
|
33
|
+
cacheEnabled?: boolean;
|
|
34
|
+
cacheTTL?: number;
|
|
35
|
+
};
|
|
36
|
+
tracking?: {
|
|
37
|
+
enabled?: boolean;
|
|
38
|
+
domain?: string;
|
|
39
|
+
};
|
|
40
|
+
compliance?: {
|
|
41
|
+
unsubscribeLink?: boolean;
|
|
42
|
+
footerRequired?: boolean;
|
|
43
|
+
};
|
|
44
|
+
magicLink?: {
|
|
45
|
+
secret: string;
|
|
46
|
+
expirationMinutes?: number;
|
|
47
|
+
issuer?: string;
|
|
48
|
+
};
|
|
49
|
+
retry?: {
|
|
50
|
+
maxRetries?: number;
|
|
51
|
+
initialDelayMs?: number;
|
|
52
|
+
maxDelayMs?: number;
|
|
53
|
+
jitter?: boolean;
|
|
54
|
+
enableMetrics?: boolean;
|
|
55
|
+
};
|
|
56
|
+
validation?: {
|
|
57
|
+
validateRecipients?: boolean;
|
|
58
|
+
strict?: boolean;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export interface EmailAddress {
|
|
62
|
+
email: string;
|
|
63
|
+
name?: string;
|
|
64
|
+
}
|
|
65
|
+
export interface EmailAttachment {
|
|
66
|
+
filename: string;
|
|
67
|
+
content: Buffer | string;
|
|
68
|
+
contentType?: string;
|
|
69
|
+
encoding?: string;
|
|
70
|
+
}
|
|
71
|
+
export interface EmailRequest {
|
|
72
|
+
from: EmailAddress | string;
|
|
73
|
+
to: EmailAddress[] | string[];
|
|
74
|
+
cc?: EmailAddress[] | string[];
|
|
75
|
+
bcc?: EmailAddress[] | string[];
|
|
76
|
+
subject: string;
|
|
77
|
+
html?: string;
|
|
78
|
+
text?: string;
|
|
79
|
+
templateId?: string;
|
|
80
|
+
templateData?: TemplateContext;
|
|
81
|
+
attachments?: EmailAttachment[];
|
|
82
|
+
headers?: Record<string, string>;
|
|
83
|
+
tags?: string[];
|
|
84
|
+
metadata?: Record<string, any>;
|
|
85
|
+
priority?: 'high' | 'normal' | 'low';
|
|
86
|
+
scheduledAt?: Date;
|
|
87
|
+
provider?: EmailProvider;
|
|
88
|
+
}
|
|
89
|
+
export interface EmailResult {
|
|
90
|
+
success: boolean;
|
|
91
|
+
messageId?: string;
|
|
92
|
+
provider?: EmailProvider;
|
|
93
|
+
error?: string;
|
|
94
|
+
timestamp: Date;
|
|
95
|
+
}
|
|
96
|
+
export interface SendEmailResult extends EmailResult {
|
|
97
|
+
deliveryId?: string;
|
|
98
|
+
queuedForLater?: boolean;
|
|
99
|
+
}
|
|
100
|
+
export interface EmailTemplate {
|
|
101
|
+
id: string;
|
|
102
|
+
name: string;
|
|
103
|
+
subject: string;
|
|
104
|
+
html: string;
|
|
105
|
+
text?: string;
|
|
106
|
+
variables: string[];
|
|
107
|
+
createdAt: Date;
|
|
108
|
+
updatedAt: Date;
|
|
109
|
+
version: number;
|
|
110
|
+
}
|
|
111
|
+
export interface TemplateCreateRequest {
|
|
112
|
+
name: string;
|
|
113
|
+
subject: string;
|
|
114
|
+
html: string;
|
|
115
|
+
text?: string;
|
|
116
|
+
}
|
|
117
|
+
export interface TemplateUpdateRequest {
|
|
118
|
+
subject?: string;
|
|
119
|
+
html?: string;
|
|
120
|
+
text?: string;
|
|
121
|
+
}
|
|
122
|
+
export declare enum DeliveryStatus {
|
|
123
|
+
QUEUED = "queued",
|
|
124
|
+
SENDING = "sending",
|
|
125
|
+
SENT = "sent",
|
|
126
|
+
DELIVERED = "delivered",
|
|
127
|
+
OPENED = "opened",
|
|
128
|
+
CLICKED = "clicked",
|
|
129
|
+
BOUNCED = "bounced",
|
|
130
|
+
FAILED = "failed",
|
|
131
|
+
UNSUBSCRIBED = "unsubscribed"
|
|
132
|
+
}
|
|
133
|
+
export interface DeliveryRecord {
|
|
134
|
+
id: string;
|
|
135
|
+
messageId: string;
|
|
136
|
+
to: string;
|
|
137
|
+
from: string;
|
|
138
|
+
subject: string;
|
|
139
|
+
provider: EmailProvider;
|
|
140
|
+
status: DeliveryStatus;
|
|
141
|
+
templateId?: string;
|
|
142
|
+
metadata?: Record<string, any>;
|
|
143
|
+
sentAt?: Date;
|
|
144
|
+
deliveredAt?: Date;
|
|
145
|
+
openedAt?: Date;
|
|
146
|
+
clickedAt?: Date;
|
|
147
|
+
bouncedAt?: Date;
|
|
148
|
+
error?: string;
|
|
149
|
+
createdAt: Date;
|
|
150
|
+
updatedAt: Date;
|
|
151
|
+
}
|
|
152
|
+
export interface DeliveryEvent {
|
|
153
|
+
deliveryId: string;
|
|
154
|
+
event: DeliveryStatus;
|
|
155
|
+
timestamp: Date;
|
|
156
|
+
metadata?: Record<string, any>;
|
|
157
|
+
}
|
|
158
|
+
export interface DeliveryStats {
|
|
159
|
+
total: number;
|
|
160
|
+
sent: number;
|
|
161
|
+
delivered: number;
|
|
162
|
+
opened: number;
|
|
163
|
+
clicked: number;
|
|
164
|
+
bounced: number;
|
|
165
|
+
failed: number;
|
|
166
|
+
openRate: number;
|
|
167
|
+
clickRate: number;
|
|
168
|
+
bounceRate: number;
|
|
169
|
+
}
|
|
170
|
+
export interface Subscriber {
|
|
171
|
+
id: string;
|
|
172
|
+
email: string;
|
|
173
|
+
name?: string;
|
|
174
|
+
status: SubscriberStatus;
|
|
175
|
+
lists: string[];
|
|
176
|
+
tags?: string[];
|
|
177
|
+
metadata?: Record<string, any>;
|
|
178
|
+
subscribedAt: Date;
|
|
179
|
+
unsubscribedAt?: Date;
|
|
180
|
+
createdAt: Date;
|
|
181
|
+
updatedAt: Date;
|
|
182
|
+
}
|
|
183
|
+
export declare enum SubscriberStatus {
|
|
184
|
+
ACTIVE = "active",
|
|
185
|
+
UNSUBSCRIBED = "unsubscribed",
|
|
186
|
+
BOUNCED = "bounced",
|
|
187
|
+
COMPLAINED = "complained"
|
|
188
|
+
}
|
|
189
|
+
export interface SubscriberList {
|
|
190
|
+
id: string;
|
|
191
|
+
name: string;
|
|
192
|
+
description?: string;
|
|
193
|
+
subscriberCount: number;
|
|
194
|
+
createdAt: Date;
|
|
195
|
+
updatedAt: Date;
|
|
196
|
+
}
|
|
197
|
+
export interface SubscriberCreateRequest {
|
|
198
|
+
email: string;
|
|
199
|
+
name?: string;
|
|
200
|
+
lists?: string[];
|
|
201
|
+
tags?: string[];
|
|
202
|
+
metadata?: Record<string, any>;
|
|
203
|
+
}
|
|
204
|
+
export interface SubscriberUpdateRequest {
|
|
205
|
+
name?: string;
|
|
206
|
+
status?: SubscriberStatus;
|
|
207
|
+
lists?: string[];
|
|
208
|
+
tags?: string[];
|
|
209
|
+
metadata?: Record<string, any>;
|
|
210
|
+
}
|
|
211
|
+
export interface WebhookEvent {
|
|
212
|
+
provider: EmailProvider;
|
|
213
|
+
event: string;
|
|
214
|
+
messageId: string;
|
|
215
|
+
timestamp: Date;
|
|
216
|
+
data: Record<string, any>;
|
|
217
|
+
}
|
|
218
|
+
export interface WebhookHandler {
|
|
219
|
+
(event: WebhookEvent): Promise<void>;
|
|
220
|
+
}
|
|
221
|
+
export { EmailServiceError, ProviderError, TemplateError, DeliveryError, } from './errors.js';
|
|
222
|
+
export type { EmailServiceErrorCode, EmailServiceErrorOptions, } from './errors.js';
|
|
223
|
+
export interface MagicLinkEmail {
|
|
224
|
+
recipient: string;
|
|
225
|
+
purpose: string;
|
|
226
|
+
redirectUrl: string;
|
|
227
|
+
subject?: string;
|
|
228
|
+
fromEmail?: string;
|
|
229
|
+
template?: string;
|
|
230
|
+
templateData?: TemplateContext;
|
|
231
|
+
customData?: Record<string, any>;
|
|
232
|
+
expirationMinutes?: number;
|
|
233
|
+
provider?: EmailProvider;
|
|
234
|
+
}
|
|
235
|
+
export interface MagicLinkResult {
|
|
236
|
+
success: boolean;
|
|
237
|
+
magicLink?: string;
|
|
238
|
+
token?: string;
|
|
239
|
+
expiresAt?: Date;
|
|
240
|
+
error?: string;
|
|
241
|
+
emailResult?: SendEmailResult;
|
|
242
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright (c) 2025 Bernier LLC
|
|
3
|
+
|
|
4
|
+
This file is licensed to the client under a limited-use license.
|
|
5
|
+
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
+
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
+
*/
|
|
8
|
+
// ===== Delivery Tracking =====
|
|
9
|
+
export var DeliveryStatus;
|
|
10
|
+
(function (DeliveryStatus) {
|
|
11
|
+
DeliveryStatus["QUEUED"] = "queued";
|
|
12
|
+
DeliveryStatus["SENDING"] = "sending";
|
|
13
|
+
DeliveryStatus["SENT"] = "sent";
|
|
14
|
+
DeliveryStatus["DELIVERED"] = "delivered";
|
|
15
|
+
DeliveryStatus["OPENED"] = "opened";
|
|
16
|
+
DeliveryStatus["CLICKED"] = "clicked";
|
|
17
|
+
DeliveryStatus["BOUNCED"] = "bounced";
|
|
18
|
+
DeliveryStatus["FAILED"] = "failed";
|
|
19
|
+
DeliveryStatus["UNSUBSCRIBED"] = "unsubscribed";
|
|
20
|
+
})(DeliveryStatus || (DeliveryStatus = {}));
|
|
21
|
+
export var SubscriberStatus;
|
|
22
|
+
(function (SubscriberStatus) {
|
|
23
|
+
SubscriberStatus["ACTIVE"] = "active";
|
|
24
|
+
SubscriberStatus["UNSUBSCRIBED"] = "unsubscribed";
|
|
25
|
+
SubscriberStatus["BOUNCED"] = "bounced";
|
|
26
|
+
SubscriberStatus["COMPLAINED"] = "complained";
|
|
27
|
+
})(SubscriberStatus || (SubscriberStatus = {}));
|
|
28
|
+
// ===== Errors =====
|
|
29
|
+
// Re-exported from ./errors for backward-compat import paths.
|
|
30
|
+
export { EmailServiceError, ProviderError, TemplateError, DeliveryError, } from './errors.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bernierllc/email-service",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.12",
|
|
4
4
|
"description": "Comprehensive email service orchestrating template management, multi-provider delivery, tracking, and subscriber management",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -26,14 +26,14 @@
|
|
|
26
26
|
"author": "Bernier LLC",
|
|
27
27
|
"license": "PROPRIETARY",
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@bernierllc/database-adapter": "^1.5.2",
|
|
30
29
|
"@bernierllc/config-manager": "^1.4.0",
|
|
31
|
-
"@bernierllc/email-parser": "^0.7.0",
|
|
32
30
|
"@bernierllc/crypto-utils": "^1.4.0",
|
|
33
|
-
"@bernierllc/
|
|
34
|
-
"@bernierllc/
|
|
35
|
-
"@bernierllc/
|
|
31
|
+
"@bernierllc/database-adapter": "^1.5.3",
|
|
32
|
+
"@bernierllc/email-parser": "^0.7.0",
|
|
33
|
+
"@bernierllc/email-sender": "^5.14.0",
|
|
36
34
|
"@bernierllc/email-validator": "^3.4.0",
|
|
35
|
+
"@bernierllc/logger": "^2.0.1",
|
|
36
|
+
"@bernierllc/queue-manager": "^1.6.0",
|
|
37
37
|
"@bernierllc/retry-metrics": "^0.5.0",
|
|
38
38
|
"@bernierllc/retry-policy": "^0.7.0",
|
|
39
39
|
"@bernierllc/retry-state": "^0.5.0",
|