@contentgrowth/content-emailing 0.4.0 → 0.5.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.
Files changed (46) hide show
  1. package/dist/backend/EmailService.cjs +728 -0
  2. package/dist/backend/EmailService.cjs.map +1 -0
  3. package/dist/backend/EmailService.js +694 -0
  4. package/dist/backend/EmailService.js.map +1 -0
  5. package/dist/backend/EmailingCacheDO.cjs +390 -0
  6. package/dist/backend/EmailingCacheDO.cjs.map +1 -0
  7. package/dist/backend/EmailingCacheDO.js +365 -0
  8. package/dist/backend/EmailingCacheDO.js.map +1 -0
  9. package/dist/backend/routes/index.cjs +992 -0
  10. package/dist/backend/routes/index.cjs.map +1 -0
  11. package/dist/backend/routes/index.js +956 -0
  12. package/dist/backend/routes/index.js.map +1 -0
  13. package/dist/cli.cjs +53 -0
  14. package/dist/cli.cjs.map +1 -0
  15. package/dist/cli.js +53 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/common/index.cjs +267 -0
  18. package/dist/common/index.cjs.map +1 -0
  19. package/{src/common/htmlWrapper.js → dist/common/index.js} +75 -18
  20. package/dist/common/index.js.map +1 -0
  21. package/dist/index.cjs +1537 -0
  22. package/dist/index.cjs.map +1 -0
  23. package/dist/index.js +1488 -0
  24. package/dist/index.js.map +1 -0
  25. package/package.json +30 -15
  26. package/examples/.env.example +0 -16
  27. package/examples/README.md +0 -55
  28. package/examples/mocks/MockD1.js +0 -311
  29. package/examples/mocks/MockEmailSender.js +0 -64
  30. package/examples/mocks/index.js +0 -5
  31. package/examples/package-lock.json +0 -73
  32. package/examples/package.json +0 -18
  33. package/examples/portal/index.html +0 -919
  34. package/examples/server.js +0 -314
  35. package/release.sh +0 -56
  36. package/src/backend/EmailService.js +0 -537
  37. package/src/backend/EmailingCacheDO.js +0 -466
  38. package/src/backend/routes/index.js +0 -30
  39. package/src/backend/routes/templates.js +0 -98
  40. package/src/backend/routes/tracking.js +0 -215
  41. package/src/backend/routes.js +0 -98
  42. package/src/common/index.js +0 -11
  43. package/src/common/utils.js +0 -141
  44. package/src/frontend/TemplateEditor.jsx +0 -117
  45. package/src/frontend/TemplateManager.jsx +0 -117
  46. package/src/index.js +0 -24
@@ -0,0 +1,728 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/backend/EmailService.js
30
+ var EmailService_exports = {};
31
+ __export(EmailService_exports, {
32
+ EmailService: () => EmailService
33
+ });
34
+ module.exports = __toCommonJS(EmailService_exports);
35
+ var import_marked = require("marked");
36
+ var import_mustache = __toESM(require("mustache"), 1);
37
+
38
+ // src/common/htmlWrapper.js
39
+ function wrapInEmailTemplate(contentHtml, subject, data = {}) {
40
+ const portalUrl = data.portalUrl || "https://app.x0start.com";
41
+ const unsubscribeUrl = data.unsubscribeUrl || "{{unsubscribe_url}}";
42
+ const brandName = data.brandName || "X0 Start";
43
+ return `
44
+ <!DOCTYPE html>
45
+ <html lang="en">
46
+ <head>
47
+ <meta charset="UTF-8">
48
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
49
+ <title>${subject}</title>
50
+ <style>
51
+ body {
52
+ margin: 0;
53
+ padding: 0;
54
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
55
+ background-color: #f5f5f5;
56
+ line-height: 1.6;
57
+ }
58
+ .email-wrapper {
59
+ background-color: #f5f5f5;
60
+ padding: 40px 20px;
61
+ }
62
+ .email-container {
63
+ max-width: 600px;
64
+ margin: 0 auto;
65
+ background-color: #ffffff;
66
+ border-radius: 8px;
67
+ overflow: hidden;
68
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
69
+ }
70
+ .email-header {
71
+ padding: 40px 40px 20px;
72
+ text-align: center;
73
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
74
+ color: #ffffff;
75
+ }
76
+ .email-header h1 {
77
+ margin: 0;
78
+ font-size: 28px;
79
+ font-weight: 600;
80
+ }
81
+ .email-content {
82
+ padding: 30px 40px;
83
+ color: #333333;
84
+ }
85
+ .email-content h1 {
86
+ font-size: 24px;
87
+ margin-top: 0;
88
+ margin-bottom: 20px;
89
+ color: #333333;
90
+ }
91
+ .email-content h2 {
92
+ font-size: 20px;
93
+ margin-top: 30px;
94
+ margin-bottom: 15px;
95
+ color: #333333;
96
+ }
97
+ .email-content h3 {
98
+ font-size: 16px;
99
+ margin-top: 20px;
100
+ margin-bottom: 10px;
101
+ color: #333333;
102
+ }
103
+ .email-content p {
104
+ margin: 0 0 15px;
105
+ color: #666666;
106
+ }
107
+ .email-content a {
108
+ color: #667eea;
109
+ text-decoration: none;
110
+ }
111
+ .email-content ul, .email-content ol {
112
+ margin: 0 0 15px;
113
+ padding-left: 25px;
114
+ }
115
+ .email-content li {
116
+ margin-bottom: 8px;
117
+ color: #666666;
118
+ }
119
+ .email-content blockquote {
120
+ margin: 20px 0;
121
+ padding: 15px 20px;
122
+ background-color: #f8f9fa;
123
+ border-left: 4px solid #667eea;
124
+ color: #666666;
125
+ }
126
+ .email-content code {
127
+ padding: 2px 6px;
128
+ background-color: #f8f9fa;
129
+ border-radius: 3px;
130
+ font-family: 'Courier New', monospace;
131
+ font-size: 14px;
132
+ }
133
+ .email-content pre {
134
+ padding: 15px;
135
+ background-color: #f8f9fa;
136
+ border-radius: 6px;
137
+ overflow-x: auto;
138
+ }
139
+ .email-content pre code {
140
+ padding: 0;
141
+ background: none;
142
+ }
143
+ .btn {
144
+ display: inline-block;
145
+ padding: 12px 24px;
146
+ background-color: #667eea;
147
+ color: #ffffff !important;
148
+ text-decoration: none;
149
+ border-radius: 6px;
150
+ font-weight: 600;
151
+ margin: 10px 0;
152
+ }
153
+ .btn:hover {
154
+ background-color: #5568d3;
155
+ }
156
+ .email-footer {
157
+ padding: 20px 40px;
158
+ background-color: #f8f9fa;
159
+ text-align: center;
160
+ font-size: 12px;
161
+ color: #666666;
162
+ }
163
+ .email-footer a {
164
+ color: #667eea;
165
+ text-decoration: none;
166
+ }
167
+ hr {
168
+ border: none;
169
+ border-top: 1px solid #e0e0e0;
170
+ margin: 30px 0;
171
+ }
172
+ </style>
173
+ </head>
174
+ <body>
175
+ <div class="email-wrapper">
176
+ <div class="email-container">
177
+ <div class="email-content">
178
+ ${contentHtml}
179
+ </div>
180
+ <div class="email-footer">
181
+ <p style="margin: 0 0 10px;">
182
+ You're receiving this email from ${brandName}.
183
+ </p>
184
+ <p style="margin: 0;">
185
+ <a href="${unsubscribeUrl}">Unsubscribe</a> |
186
+ <a href="${portalUrl}/settings/notifications">Manage Preferences</a>
187
+ </p>
188
+ </div>
189
+ </div>
190
+ </div>
191
+ </body>
192
+ </html>
193
+ `.trim();
194
+ }
195
+
196
+ // src/backend/EmailingCacheDO.js
197
+ function createDOCacheProvider(doStub, instanceName = "global") {
198
+ if (!doStub) {
199
+ return null;
200
+ }
201
+ const stub = doStub.get(doStub.idFromName(instanceName));
202
+ return {
203
+ async getTemplate(templateId) {
204
+ try {
205
+ const response = await stub.fetch(`http://do/get?templateId=${templateId}`);
206
+ const data = await response.json();
207
+ return data.template || null;
208
+ } catch (e) {
209
+ console.warn("[DOCacheProvider] Failed to get template:", e);
210
+ return null;
211
+ }
212
+ },
213
+ async getSettings(profile, tenantId) {
214
+ const key = `${profile}:${tenantId || ""}`;
215
+ try {
216
+ const response = await stub.fetch(`http://do/settings/get?key=${encodeURIComponent(key)}`);
217
+ const data = await response.json();
218
+ return data.settings || null;
219
+ } catch (e) {
220
+ return null;
221
+ }
222
+ },
223
+ async putSettings(profile, tenantId, settings) {
224
+ const key = `${profile}:${tenantId || ""}`;
225
+ try {
226
+ await stub.fetch("http://do/settings/put", {
227
+ method: "POST",
228
+ headers: { "Content-Type": "application/json" },
229
+ body: JSON.stringify({ key, settings })
230
+ });
231
+ } catch (e) {
232
+ console.warn("[DOCacheProvider] Failed to cache settings:", e);
233
+ }
234
+ },
235
+ async putTemplate(template) {
236
+ try {
237
+ await stub.fetch("http://do/invalidate", {
238
+ method: "POST",
239
+ headers: { "Content-Type": "application/json" },
240
+ body: JSON.stringify({ templateId: template.template_id })
241
+ });
242
+ } catch (e) {
243
+ console.warn("[DOCacheProvider] Failed to invalidate template:", e);
244
+ }
245
+ },
246
+ async deleteTemplate(templateId) {
247
+ try {
248
+ await stub.fetch("http://do/invalidate", {
249
+ method: "POST",
250
+ headers: { "Content-Type": "application/json" },
251
+ body: JSON.stringify({ templateId })
252
+ });
253
+ } catch (e) {
254
+ console.warn("[DOCacheProvider] Failed to invalidate template:", e);
255
+ }
256
+ },
257
+ async invalidateSettings(profile, tenantId) {
258
+ const key = `${profile}:${tenantId || ""}`;
259
+ try {
260
+ await stub.fetch("http://do/settings/invalidate", {
261
+ method: "POST",
262
+ headers: { "Content-Type": "application/json" },
263
+ body: JSON.stringify({ key })
264
+ });
265
+ } catch (e) {
266
+ console.warn("[DOCacheProvider] Failed to invalidate settings:", e);
267
+ }
268
+ }
269
+ };
270
+ }
271
+
272
+ // src/backend/EmailService.js
273
+ var EmailService = class {
274
+ /**
275
+ * @param {Object} env - Cloudflare environment bindings (DB, etc.)
276
+ * @param {Object} config - Configuration options
277
+ * @param {string} [config.emailTablePrefix='system_email_'] - Prefix for D1 tables
278
+ * @param {Object} [config.defaults] - Default settings (fromName, fromAddress)
279
+ * @param {Object} [cacheProvider] - Optional cache interface (DO stub or KV wrapper)
280
+ */
281
+ constructor(env, config = {}, cacheProvider = null) {
282
+ var _a, _b, _c;
283
+ this.env = env;
284
+ this.db = env.DB;
285
+ this.config = {
286
+ emailTablePrefix: config.emailTablePrefix || config.tableNamePrefix || "system_email_",
287
+ defaults: config.defaults || {
288
+ fromName: "System",
289
+ fromAddress: "noreply@example.com",
290
+ provider: "mailchannels"
291
+ },
292
+ // Loader function to fetch settings from backend (DB, KV, etc.)
293
+ // Signature: async (profile, tenantId) => SettingsObject
294
+ settingsLoader: config.settingsLoader || null,
295
+ // Updater function to save settings to backend
296
+ // Signature: async (profile, tenantId, settings) => void
297
+ settingsUpdater: config.settingsUpdater || null,
298
+ // Branding configuration for email templates
299
+ branding: {
300
+ brandName: ((_a = config.branding) == null ? void 0 : _a.brandName) || "Your App",
301
+ portalUrl: ((_b = config.branding) == null ? void 0 : _b.portalUrl) || "https://app.example.com",
302
+ primaryColor: ((_c = config.branding) == null ? void 0 : _c.primaryColor) || "#667eea",
303
+ ...config.branding
304
+ },
305
+ ...config
306
+ };
307
+ if (!cacheProvider && env.EMAIL_TEMPLATE_CACHE) {
308
+ this.cache = createDOCacheProvider(env.EMAIL_TEMPLATE_CACHE);
309
+ } else {
310
+ this.cache = cacheProvider;
311
+ }
312
+ }
313
+ // --- Configuration & Settings ---
314
+ /**
315
+ * Load email configuration
316
+ * @param {string} profile - 'system' or 'tenant' (or custom profile string)
317
+ * @param {string} tenantId - Context ID (optional)
318
+ * @returns {Promise<Object>} Email configuration
319
+ */
320
+ async loadSettings(profile = "system", tenantId = null) {
321
+ if (this.cache && this.cache.getSettings) {
322
+ try {
323
+ const cached = await this.cache.getSettings(profile, tenantId);
324
+ if (cached) return this._normalizeConfig(cached);
325
+ } catch (e) {
326
+ }
327
+ }
328
+ let settings = null;
329
+ if (this.config.settingsLoader) {
330
+ try {
331
+ settings = await this.config.settingsLoader(profile, tenantId);
332
+ } catch (e) {
333
+ console.warn("[EmailService] settingsLoader failed:", e);
334
+ }
335
+ }
336
+ if (settings) {
337
+ if (this.cache && this.cache.putSettings) {
338
+ try {
339
+ this.cache.putSettings(profile, tenantId, settings);
340
+ } catch (e) {
341
+ }
342
+ }
343
+ return this._normalizeConfig(settings);
344
+ }
345
+ return {
346
+ ...this.config.defaults
347
+ };
348
+ }
349
+ /**
350
+ * Normalize config keys to standard format
351
+ * Handles both snake_case (DB) and camelCase inputs
352
+ */
353
+ _normalizeConfig(config) {
354
+ return {
355
+ provider: config.email_provider || config.provider || this.config.defaults.provider,
356
+ fromAddress: config.email_from_address || config.fromAddress || this.config.defaults.fromAddress,
357
+ fromName: config.email_from_name || config.fromName || this.config.defaults.fromName,
358
+ // Provider-specific settings (normalize DB keys to service keys)
359
+ sendgridApiKey: config.sendgrid_api_key || config.sendgridApiKey,
360
+ resendApiKey: config.resend_api_key || config.resendApiKey,
361
+ sendpulseClientId: config.sendpulse_client_id || config.sendpulseClientId,
362
+ sendpulseClientSecret: config.sendpulse_client_secret || config.sendpulseClientSecret,
363
+ // SMTP
364
+ smtpHost: config.smtp_host || config.smtpHost,
365
+ smtpPort: config.smtp_port || config.smtpPort,
366
+ smtpUsername: config.smtp_username || config.smtpUsername,
367
+ smtpPassword: config.smtp_password || config.smtpPassword,
368
+ // Tracking
369
+ trackingUrl: config.tracking_url || config.trackingUrl,
370
+ // Pass through others
371
+ // Pass through others
372
+ ...config,
373
+ smtpSecure: config.smtp_secure === "true"
374
+ };
375
+ }
376
+ // --- Template Management ---
377
+ async getTemplate(templateId) {
378
+ if (this.cache) {
379
+ try {
380
+ const cached = await this.cache.getTemplate(templateId);
381
+ if (cached) return cached;
382
+ } catch (e) {
383
+ console.warn("[EmailService] Template cache lookup failed:", e);
384
+ }
385
+ }
386
+ const table = `${this.config.emailTablePrefix}templates`;
387
+ return await this.db.prepare(`SELECT * FROM ${table} WHERE template_id = ?`).bind(templateId).first();
388
+ }
389
+ async getAllTemplates() {
390
+ const table = `${this.config.emailTablePrefix}templates`;
391
+ const result = await this.db.prepare(`SELECT * FROM ${table} ORDER BY template_name`).all();
392
+ return result.results || [];
393
+ }
394
+ /**
395
+ * Save email configuration
396
+ * @param {Object} settings - Config object
397
+ * @param {string} profile - 'system' or 'tenant'
398
+ * @param {string} tenantId - Context ID
399
+ */
400
+ async saveSettings(settings, profile = "system", tenantId = null) {
401
+ if (this.config.settingsUpdater) {
402
+ try {
403
+ await this.config.settingsUpdater(profile, tenantId, settings);
404
+ } catch (e) {
405
+ console.error("[EmailService] settingsUpdater failed:", e);
406
+ throw e;
407
+ }
408
+ } else if (profile === "system" && this.db) {
409
+ }
410
+ if (this.cache && this.cache.invalidateSettings) {
411
+ try {
412
+ await this.cache.invalidateSettings(profile, tenantId);
413
+ } catch (e) {
414
+ console.warn("[EmailService] Failed to invalidate settings cache:", e);
415
+ }
416
+ }
417
+ }
418
+ async saveTemplate(template, userId = "system") {
419
+ const table = `${this.config.emailTablePrefix}templates`;
420
+ const now = Math.floor(Date.now() / 1e3);
421
+ const existing = await this.getTemplate(template.template_id);
422
+ if (existing) {
423
+ await this.db.prepare(`
424
+ UPDATE ${table} SET
425
+ template_name = ?, template_type = ?, subject_template = ?,
426
+ body_markdown = ?, variables = ?, description = ?, is_active = ?,
427
+ updated_at = ?, updated_by = ?
428
+ WHERE template_id = ?
429
+ `).bind(
430
+ template.template_name,
431
+ template.template_type,
432
+ template.subject_template,
433
+ template.body_markdown,
434
+ template.variables,
435
+ template.description,
436
+ template.is_active,
437
+ now,
438
+ userId,
439
+ template.template_id
440
+ ).run();
441
+ } else {
442
+ await this.db.prepare(`
443
+ INSERT INTO ${table} (
444
+ template_id, template_name, template_type, subject_template,
445
+ body_markdown, variables, description, is_active, created_at, updated_at, updated_by
446
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
447
+ `).bind(
448
+ template.template_id,
449
+ template.template_name,
450
+ template.template_type,
451
+ template.subject_template,
452
+ template.body_markdown,
453
+ template.variables || "[]",
454
+ template.description,
455
+ template.is_active || 1,
456
+ now,
457
+ now,
458
+ userId
459
+ ).run();
460
+ }
461
+ if (this.cache) {
462
+ await this.cache.putTemplate(template);
463
+ }
464
+ }
465
+ async deleteTemplate(templateId) {
466
+ const table = `${this.config.emailTablePrefix}templates`;
467
+ await this.db.prepare(`DELETE FROM ${table} WHERE template_id = ?`).bind(templateId).run();
468
+ if (this.cache) {
469
+ await this.cache.deleteTemplate(templateId);
470
+ }
471
+ }
472
+ // --- Rendering ---
473
+ async renderTemplate(templateId, data) {
474
+ const template = await this.getTemplate(templateId);
475
+ if (!template) throw new Error(`Template not found: ${templateId}`);
476
+ const subject = import_mustache.default.render(template.subject_template, data);
477
+ const markdown = import_mustache.default.render(template.body_markdown, data);
478
+ import_marked.marked.use({ mangle: false, headerIds: false });
479
+ const htmlContent = import_marked.marked.parse(markdown);
480
+ const html = this.wrapInBaseTemplate(htmlContent, subject, data);
481
+ const plainText = markdown.replace(/<[^>]*>/g, "");
482
+ return { subject, html, plainText };
483
+ }
484
+ wrapInBaseTemplate(content, subject, data = {}) {
485
+ const templateData = {
486
+ ...data,
487
+ brandName: data.brandName || this.config.branding.brandName,
488
+ portalUrl: data.portalUrl || this.config.branding.portalUrl,
489
+ unsubscribeUrl: data.unsubscribeUrl || "{{unsubscribe_url}}"
490
+ };
491
+ return wrapInEmailTemplate(content, subject, templateData);
492
+ }
493
+ // --- Delivery ---
494
+ /**
495
+ * Send a single email
496
+ * @param {Object} params - Email parameters
497
+ * @param {string} params.to - Recipient email
498
+ * @param {string} params.subject - Email subject
499
+ * @param {string} params.html - HTML body
500
+ * @param {string} params.text - Plain text body
501
+ * @param {string} [params.provider] - Override provider
502
+ * @param {string} [params.profile='system'] - 'system' or 'tenant'
503
+ * @param {string} [params.tenantId] - Required if profile is 'tenant'
504
+ * @param {Object} [params.metadata] - Additional metadata
505
+ * @returns {Promise<Object>} Delivery result
506
+ */
507
+ async sendEmail({ to, subject, html, htmlBody, text, textBody, provider, profile = "system", tenantId = null, metadata = {} }) {
508
+ const htmlContent = html || htmlBody;
509
+ const textContent = text || textBody;
510
+ try {
511
+ const settings = await this.loadSettings(profile, tenantId);
512
+ const useProvider = provider || settings.provider || "mailchannels";
513
+ let result;
514
+ switch (useProvider) {
515
+ case "mailchannels":
516
+ result = await this.sendViaMailChannels(to, subject, htmlContent, textContent, settings, metadata);
517
+ break;
518
+ case "sendgrid":
519
+ result = await this.sendViaSendGrid(to, subject, htmlContent, textContent, settings, metadata);
520
+ break;
521
+ case "resend":
522
+ result = await this.sendViaResend(to, subject, htmlContent, textContent, settings, metadata);
523
+ break;
524
+ case "sendpulse":
525
+ result = await this.sendViaSendPulse(to, subject, htmlContent, textContent, settings, metadata);
526
+ break;
527
+ default:
528
+ console.error(`[EmailService] Unknown provider: ${useProvider}`);
529
+ return { success: false, error: `Unknown email provider: ${useProvider}` };
530
+ }
531
+ if (result) {
532
+ return { success: true, messageId: crypto.randomUUID() };
533
+ } else {
534
+ console.error("[EmailService] Failed to send email to:", to);
535
+ return { success: false, error: "Failed to send email" };
536
+ }
537
+ } catch (error) {
538
+ console.error("[EmailService] Error sending email:", error);
539
+ return { success: false, error: error.message };
540
+ }
541
+ }
542
+ /**
543
+ * Send multiple emails in batch
544
+ * @param {Array} emails - Array of email objects
545
+ * @returns {Promise<Array>} Array of delivery results
546
+ */
547
+ async sendBatch(emails) {
548
+ console.log("[EmailService] Sending batch of", emails.length, "emails");
549
+ const results = await Promise.all(
550
+ emails.map((email) => this.sendEmail(email))
551
+ );
552
+ return results;
553
+ }
554
+ /**
555
+ * Send email via MailChannels HTTP API
556
+ * MailChannels is specifically designed for Cloudflare Workers
557
+ */
558
+ async sendViaMailChannels(to, subject, html, text, settings, metadata) {
559
+ try {
560
+ const response = await fetch("https://api.mailchannels.net/tx/v1/send", {
561
+ method: "POST",
562
+ headers: { "Content-Type": "application/json" },
563
+ body: JSON.stringify({
564
+ personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
565
+ from: { email: settings.fromAddress, name: settings.fromName },
566
+ subject,
567
+ content: [
568
+ { type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") },
569
+ { type: "text/html", value: html }
570
+ ]
571
+ })
572
+ });
573
+ if (response.status === 202) {
574
+ return true;
575
+ } else {
576
+ const contentType = response.headers.get("content-type");
577
+ const errorBody = (contentType == null ? void 0 : contentType.includes("application/json")) ? await response.json() : await response.text();
578
+ console.error("[EmailService] MailChannels error:", response.status, errorBody);
579
+ return false;
580
+ }
581
+ } catch (error) {
582
+ console.error("[EmailService] MailChannels exception:", error.message);
583
+ return false;
584
+ }
585
+ }
586
+ /**
587
+ * Send email via SendGrid HTTP API
588
+ */
589
+ async sendViaSendGrid(to, subject, html, text, settings, metadata) {
590
+ try {
591
+ if (!settings.sendgridApiKey) {
592
+ console.error("[EmailService] SendGrid API key missing");
593
+ return false;
594
+ }
595
+ const response = await fetch("https://api.sendgrid.com/v3/mail/send", {
596
+ method: "POST",
597
+ headers: {
598
+ "Authorization": `Bearer ${settings.sendgridApiKey}`,
599
+ "Content-Type": "application/json"
600
+ },
601
+ body: JSON.stringify({
602
+ personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
603
+ from: { email: settings.fromAddress, name: settings.fromName },
604
+ subject,
605
+ content: [
606
+ { type: "text/html", value: html },
607
+ { type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") }
608
+ ]
609
+ })
610
+ });
611
+ if (response.status === 202) {
612
+ return true;
613
+ } else {
614
+ const errorText = await response.text();
615
+ console.error("[EmailService] SendGrid error:", response.status, errorText);
616
+ return false;
617
+ }
618
+ } catch (error) {
619
+ console.error("[EmailService] SendGrid exception:", error.message);
620
+ return false;
621
+ }
622
+ }
623
+ /**
624
+ * Send email via Resend HTTP API
625
+ */
626
+ async sendViaResend(to, subject, html, text, settings, metadata) {
627
+ try {
628
+ if (!settings.resendApiKey) {
629
+ console.error("[EmailService] Resend API key missing");
630
+ return false;
631
+ }
632
+ const response = await fetch("https://api.resend.com/emails", {
633
+ method: "POST",
634
+ headers: {
635
+ "Authorization": `Bearer ${settings.resendApiKey}`,
636
+ "Content-Type": "application/json"
637
+ },
638
+ body: JSON.stringify({
639
+ from: `${settings.fromName} <${settings.fromAddress}>`,
640
+ to: [to],
641
+ subject,
642
+ html,
643
+ text: text || html.replace(/<[^>]*>/g, "")
644
+ })
645
+ });
646
+ if (response.ok) {
647
+ return true;
648
+ } else {
649
+ const errorText = await response.text();
650
+ console.error("[EmailService] Resend error:", response.status, errorText);
651
+ return false;
652
+ }
653
+ } catch (error) {
654
+ console.error("[EmailService] Resend exception:", error.message);
655
+ return false;
656
+ }
657
+ }
658
+ /**
659
+ * Send email via SendPulse HTTP API
660
+ * SendPulse offers 15,000 free emails/month
661
+ */
662
+ async sendViaSendPulse(to, subject, html, text, settings, metadata) {
663
+ try {
664
+ if (!settings.sendpulseClientId || !settings.sendpulseClientSecret) {
665
+ console.error("[EmailService] SendPulse credentials missing");
666
+ return false;
667
+ }
668
+ const tokenParams = new URLSearchParams({
669
+ grant_type: "client_credentials",
670
+ client_id: settings.sendpulseClientId,
671
+ client_secret: settings.sendpulseClientSecret
672
+ });
673
+ const tokenResponse = await fetch("https://api.sendpulse.com/oauth/access_token", {
674
+ method: "POST",
675
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
676
+ body: tokenParams.toString()
677
+ });
678
+ if (!tokenResponse.ok) {
679
+ const error = await tokenResponse.text();
680
+ console.error("[EmailService] SendPulse auth error:", error);
681
+ return false;
682
+ }
683
+ const tokenData = await tokenResponse.json();
684
+ if (!tokenData.access_token) {
685
+ console.error("[EmailService] SendPulse: No access token in response");
686
+ return false;
687
+ }
688
+ const { access_token } = tokenData;
689
+ const toBase64 = (str) => {
690
+ if (!str) return "";
691
+ return Buffer.from(String(str)).toString("base64");
692
+ };
693
+ const htmlSafe = html || "";
694
+ const textSafe = text || (htmlSafe ? htmlSafe.replace(/<[^>]*>/g, "") : "");
695
+ const response = await fetch("https://api.sendpulse.com/smtp/emails", {
696
+ method: "POST",
697
+ headers: {
698
+ "Authorization": `Bearer ${access_token}`,
699
+ "Content-Type": "application/json"
700
+ },
701
+ body: JSON.stringify({
702
+ email: {
703
+ html: toBase64(htmlSafe),
704
+ text: toBase64(textSafe),
705
+ subject,
706
+ from: { name: settings.fromName, email: settings.fromAddress },
707
+ to: [{ name: metadata.recipientName || "", email: to }]
708
+ }
709
+ })
710
+ });
711
+ if (response.ok) {
712
+ return true;
713
+ } else {
714
+ const errorText = await response.text();
715
+ console.error("[EmailService] SendPulse send error:", response.status, errorText);
716
+ return false;
717
+ }
718
+ } catch (error) {
719
+ console.error("[EmailService] SendPulse exception:", error.message);
720
+ return false;
721
+ }
722
+ }
723
+ };
724
+ // Annotate the CommonJS export names for ESM import in node:
725
+ 0 && (module.exports = {
726
+ EmailService
727
+ });
728
+ //# sourceMappingURL=EmailService.cjs.map