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