@contentgrowth/content-emailing 0.4.1 → 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 +27 -12
  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,956 @@
1
+ // src/backend/routes/index.js
2
+ import { Hono as Hono3 } from "hono";
3
+
4
+ // src/backend/routes/templates.js
5
+ import { Hono } from "hono";
6
+
7
+ // src/backend/EmailService.js
8
+ import { marked } from "marked";
9
+ import Mustache from "mustache";
10
+
11
+ // src/common/htmlWrapper.js
12
+ function wrapInEmailTemplate(contentHtml, subject, data = {}) {
13
+ const portalUrl = data.portalUrl || "https://app.x0start.com";
14
+ const unsubscribeUrl = data.unsubscribeUrl || "{{unsubscribe_url}}";
15
+ const brandName = data.brandName || "X0 Start";
16
+ return `
17
+ <!DOCTYPE html>
18
+ <html lang="en">
19
+ <head>
20
+ <meta charset="UTF-8">
21
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
22
+ <title>${subject}</title>
23
+ <style>
24
+ body {
25
+ margin: 0;
26
+ padding: 0;
27
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
28
+ background-color: #f5f5f5;
29
+ line-height: 1.6;
30
+ }
31
+ .email-wrapper {
32
+ background-color: #f5f5f5;
33
+ padding: 40px 20px;
34
+ }
35
+ .email-container {
36
+ max-width: 600px;
37
+ margin: 0 auto;
38
+ background-color: #ffffff;
39
+ border-radius: 8px;
40
+ overflow: hidden;
41
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
42
+ }
43
+ .email-header {
44
+ padding: 40px 40px 20px;
45
+ text-align: center;
46
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
47
+ color: #ffffff;
48
+ }
49
+ .email-header h1 {
50
+ margin: 0;
51
+ font-size: 28px;
52
+ font-weight: 600;
53
+ }
54
+ .email-content {
55
+ padding: 30px 40px;
56
+ color: #333333;
57
+ }
58
+ .email-content h1 {
59
+ font-size: 24px;
60
+ margin-top: 0;
61
+ margin-bottom: 20px;
62
+ color: #333333;
63
+ }
64
+ .email-content h2 {
65
+ font-size: 20px;
66
+ margin-top: 30px;
67
+ margin-bottom: 15px;
68
+ color: #333333;
69
+ }
70
+ .email-content h3 {
71
+ font-size: 16px;
72
+ margin-top: 20px;
73
+ margin-bottom: 10px;
74
+ color: #333333;
75
+ }
76
+ .email-content p {
77
+ margin: 0 0 15px;
78
+ color: #666666;
79
+ }
80
+ .email-content a {
81
+ color: #667eea;
82
+ text-decoration: none;
83
+ }
84
+ .email-content ul, .email-content ol {
85
+ margin: 0 0 15px;
86
+ padding-left: 25px;
87
+ }
88
+ .email-content li {
89
+ margin-bottom: 8px;
90
+ color: #666666;
91
+ }
92
+ .email-content blockquote {
93
+ margin: 20px 0;
94
+ padding: 15px 20px;
95
+ background-color: #f8f9fa;
96
+ border-left: 4px solid #667eea;
97
+ color: #666666;
98
+ }
99
+ .email-content code {
100
+ padding: 2px 6px;
101
+ background-color: #f8f9fa;
102
+ border-radius: 3px;
103
+ font-family: 'Courier New', monospace;
104
+ font-size: 14px;
105
+ }
106
+ .email-content pre {
107
+ padding: 15px;
108
+ background-color: #f8f9fa;
109
+ border-radius: 6px;
110
+ overflow-x: auto;
111
+ }
112
+ .email-content pre code {
113
+ padding: 0;
114
+ background: none;
115
+ }
116
+ .btn {
117
+ display: inline-block;
118
+ padding: 12px 24px;
119
+ background-color: #667eea;
120
+ color: #ffffff !important;
121
+ text-decoration: none;
122
+ border-radius: 6px;
123
+ font-weight: 600;
124
+ margin: 10px 0;
125
+ }
126
+ .btn:hover {
127
+ background-color: #5568d3;
128
+ }
129
+ .email-footer {
130
+ padding: 20px 40px;
131
+ background-color: #f8f9fa;
132
+ text-align: center;
133
+ font-size: 12px;
134
+ color: #666666;
135
+ }
136
+ .email-footer a {
137
+ color: #667eea;
138
+ text-decoration: none;
139
+ }
140
+ hr {
141
+ border: none;
142
+ border-top: 1px solid #e0e0e0;
143
+ margin: 30px 0;
144
+ }
145
+ </style>
146
+ </head>
147
+ <body>
148
+ <div class="email-wrapper">
149
+ <div class="email-container">
150
+ <div class="email-content">
151
+ ${contentHtml}
152
+ </div>
153
+ <div class="email-footer">
154
+ <p style="margin: 0 0 10px;">
155
+ You're receiving this email from ${brandName}.
156
+ </p>
157
+ <p style="margin: 0;">
158
+ <a href="${unsubscribeUrl}">Unsubscribe</a> |
159
+ <a href="${portalUrl}/settings/notifications">Manage Preferences</a>
160
+ </p>
161
+ </div>
162
+ </div>
163
+ </div>
164
+ </body>
165
+ </html>
166
+ `.trim();
167
+ }
168
+
169
+ // src/backend/EmailingCacheDO.js
170
+ function createDOCacheProvider(doStub, instanceName = "global") {
171
+ if (!doStub) {
172
+ return null;
173
+ }
174
+ const stub = doStub.get(doStub.idFromName(instanceName));
175
+ return {
176
+ async getTemplate(templateId) {
177
+ try {
178
+ const response = await stub.fetch(`http://do/get?templateId=${templateId}`);
179
+ const data = await response.json();
180
+ return data.template || null;
181
+ } catch (e) {
182
+ console.warn("[DOCacheProvider] Failed to get template:", e);
183
+ return null;
184
+ }
185
+ },
186
+ async getSettings(profile, tenantId) {
187
+ const key = `${profile}:${tenantId || ""}`;
188
+ try {
189
+ const response = await stub.fetch(`http://do/settings/get?key=${encodeURIComponent(key)}`);
190
+ const data = await response.json();
191
+ return data.settings || null;
192
+ } catch (e) {
193
+ return null;
194
+ }
195
+ },
196
+ async putSettings(profile, tenantId, settings) {
197
+ const key = `${profile}:${tenantId || ""}`;
198
+ try {
199
+ await stub.fetch("http://do/settings/put", {
200
+ method: "POST",
201
+ headers: { "Content-Type": "application/json" },
202
+ body: JSON.stringify({ key, settings })
203
+ });
204
+ } catch (e) {
205
+ console.warn("[DOCacheProvider] Failed to cache settings:", e);
206
+ }
207
+ },
208
+ async putTemplate(template) {
209
+ try {
210
+ await stub.fetch("http://do/invalidate", {
211
+ method: "POST",
212
+ headers: { "Content-Type": "application/json" },
213
+ body: JSON.stringify({ templateId: template.template_id })
214
+ });
215
+ } catch (e) {
216
+ console.warn("[DOCacheProvider] Failed to invalidate template:", e);
217
+ }
218
+ },
219
+ async deleteTemplate(templateId) {
220
+ try {
221
+ await stub.fetch("http://do/invalidate", {
222
+ method: "POST",
223
+ headers: { "Content-Type": "application/json" },
224
+ body: JSON.stringify({ templateId })
225
+ });
226
+ } catch (e) {
227
+ console.warn("[DOCacheProvider] Failed to invalidate template:", e);
228
+ }
229
+ },
230
+ async invalidateSettings(profile, tenantId) {
231
+ const key = `${profile}:${tenantId || ""}`;
232
+ try {
233
+ await stub.fetch("http://do/settings/invalidate", {
234
+ method: "POST",
235
+ headers: { "Content-Type": "application/json" },
236
+ body: JSON.stringify({ key })
237
+ });
238
+ } catch (e) {
239
+ console.warn("[DOCacheProvider] Failed to invalidate settings:", e);
240
+ }
241
+ }
242
+ };
243
+ }
244
+
245
+ // src/backend/EmailService.js
246
+ var EmailService = class {
247
+ /**
248
+ * @param {Object} env - Cloudflare environment bindings (DB, etc.)
249
+ * @param {Object} config - Configuration options
250
+ * @param {string} [config.emailTablePrefix='system_email_'] - Prefix for D1 tables
251
+ * @param {Object} [config.defaults] - Default settings (fromName, fromAddress)
252
+ * @param {Object} [cacheProvider] - Optional cache interface (DO stub or KV wrapper)
253
+ */
254
+ constructor(env, config = {}, cacheProvider = null) {
255
+ var _a, _b, _c;
256
+ this.env = env;
257
+ this.db = env.DB;
258
+ this.config = {
259
+ emailTablePrefix: config.emailTablePrefix || config.tableNamePrefix || "system_email_",
260
+ defaults: config.defaults || {
261
+ fromName: "System",
262
+ fromAddress: "noreply@example.com",
263
+ provider: "mailchannels"
264
+ },
265
+ // Loader function to fetch settings from backend (DB, KV, etc.)
266
+ // Signature: async (profile, tenantId) => SettingsObject
267
+ settingsLoader: config.settingsLoader || null,
268
+ // Updater function to save settings to backend
269
+ // Signature: async (profile, tenantId, settings) => void
270
+ settingsUpdater: config.settingsUpdater || null,
271
+ // Branding configuration for email templates
272
+ branding: {
273
+ brandName: ((_a = config.branding) == null ? void 0 : _a.brandName) || "Your App",
274
+ portalUrl: ((_b = config.branding) == null ? void 0 : _b.portalUrl) || "https://app.example.com",
275
+ primaryColor: ((_c = config.branding) == null ? void 0 : _c.primaryColor) || "#667eea",
276
+ ...config.branding
277
+ },
278
+ ...config
279
+ };
280
+ if (!cacheProvider && env.EMAIL_TEMPLATE_CACHE) {
281
+ this.cache = createDOCacheProvider(env.EMAIL_TEMPLATE_CACHE);
282
+ } else {
283
+ this.cache = cacheProvider;
284
+ }
285
+ }
286
+ // --- Configuration & Settings ---
287
+ /**
288
+ * Load email configuration
289
+ * @param {string} profile - 'system' or 'tenant' (or custom profile string)
290
+ * @param {string} tenantId - Context ID (optional)
291
+ * @returns {Promise<Object>} Email configuration
292
+ */
293
+ async loadSettings(profile = "system", tenantId = null) {
294
+ if (this.cache && this.cache.getSettings) {
295
+ try {
296
+ const cached = await this.cache.getSettings(profile, tenantId);
297
+ if (cached) return this._normalizeConfig(cached);
298
+ } catch (e) {
299
+ }
300
+ }
301
+ let settings = null;
302
+ if (this.config.settingsLoader) {
303
+ try {
304
+ settings = await this.config.settingsLoader(profile, tenantId);
305
+ } catch (e) {
306
+ console.warn("[EmailService] settingsLoader failed:", e);
307
+ }
308
+ }
309
+ if (settings) {
310
+ if (this.cache && this.cache.putSettings) {
311
+ try {
312
+ this.cache.putSettings(profile, tenantId, settings);
313
+ } catch (e) {
314
+ }
315
+ }
316
+ return this._normalizeConfig(settings);
317
+ }
318
+ return {
319
+ ...this.config.defaults
320
+ };
321
+ }
322
+ /**
323
+ * Normalize config keys to standard format
324
+ * Handles both snake_case (DB) and camelCase inputs
325
+ */
326
+ _normalizeConfig(config) {
327
+ return {
328
+ provider: config.email_provider || config.provider || this.config.defaults.provider,
329
+ fromAddress: config.email_from_address || config.fromAddress || this.config.defaults.fromAddress,
330
+ fromName: config.email_from_name || config.fromName || this.config.defaults.fromName,
331
+ // Provider-specific settings (normalize DB keys to service keys)
332
+ sendgridApiKey: config.sendgrid_api_key || config.sendgridApiKey,
333
+ resendApiKey: config.resend_api_key || config.resendApiKey,
334
+ sendpulseClientId: config.sendpulse_client_id || config.sendpulseClientId,
335
+ sendpulseClientSecret: config.sendpulse_client_secret || config.sendpulseClientSecret,
336
+ // SMTP
337
+ smtpHost: config.smtp_host || config.smtpHost,
338
+ smtpPort: config.smtp_port || config.smtpPort,
339
+ smtpUsername: config.smtp_username || config.smtpUsername,
340
+ smtpPassword: config.smtp_password || config.smtpPassword,
341
+ // Tracking
342
+ trackingUrl: config.tracking_url || config.trackingUrl,
343
+ // Pass through others
344
+ // Pass through others
345
+ ...config,
346
+ smtpSecure: config.smtp_secure === "true"
347
+ };
348
+ }
349
+ // --- Template Management ---
350
+ async getTemplate(templateId) {
351
+ if (this.cache) {
352
+ try {
353
+ const cached = await this.cache.getTemplate(templateId);
354
+ if (cached) return cached;
355
+ } catch (e) {
356
+ console.warn("[EmailService] Template cache lookup failed:", e);
357
+ }
358
+ }
359
+ const table = `${this.config.emailTablePrefix}templates`;
360
+ return await this.db.prepare(`SELECT * FROM ${table} WHERE template_id = ?`).bind(templateId).first();
361
+ }
362
+ async getAllTemplates() {
363
+ const table = `${this.config.emailTablePrefix}templates`;
364
+ const result = await this.db.prepare(`SELECT * FROM ${table} ORDER BY template_name`).all();
365
+ return result.results || [];
366
+ }
367
+ /**
368
+ * Save email configuration
369
+ * @param {Object} settings - Config object
370
+ * @param {string} profile - 'system' or 'tenant'
371
+ * @param {string} tenantId - Context ID
372
+ */
373
+ async saveSettings(settings, profile = "system", tenantId = null) {
374
+ if (this.config.settingsUpdater) {
375
+ try {
376
+ await this.config.settingsUpdater(profile, tenantId, settings);
377
+ } catch (e) {
378
+ console.error("[EmailService] settingsUpdater failed:", e);
379
+ throw e;
380
+ }
381
+ } else if (profile === "system" && this.db) {
382
+ }
383
+ if (this.cache && this.cache.invalidateSettings) {
384
+ try {
385
+ await this.cache.invalidateSettings(profile, tenantId);
386
+ } catch (e) {
387
+ console.warn("[EmailService] Failed to invalidate settings cache:", e);
388
+ }
389
+ }
390
+ }
391
+ async saveTemplate(template, userId = "system") {
392
+ const table = `${this.config.emailTablePrefix}templates`;
393
+ const now = Math.floor(Date.now() / 1e3);
394
+ const existing = await this.getTemplate(template.template_id);
395
+ if (existing) {
396
+ await this.db.prepare(`
397
+ UPDATE ${table} SET
398
+ template_name = ?, template_type = ?, subject_template = ?,
399
+ body_markdown = ?, variables = ?, description = ?, is_active = ?,
400
+ updated_at = ?, updated_by = ?
401
+ WHERE template_id = ?
402
+ `).bind(
403
+ template.template_name,
404
+ template.template_type,
405
+ template.subject_template,
406
+ template.body_markdown,
407
+ template.variables,
408
+ template.description,
409
+ template.is_active,
410
+ now,
411
+ userId,
412
+ template.template_id
413
+ ).run();
414
+ } else {
415
+ await this.db.prepare(`
416
+ INSERT INTO ${table} (
417
+ template_id, template_name, template_type, subject_template,
418
+ body_markdown, variables, description, is_active, created_at, updated_at, updated_by
419
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
420
+ `).bind(
421
+ template.template_id,
422
+ template.template_name,
423
+ template.template_type,
424
+ template.subject_template,
425
+ template.body_markdown,
426
+ template.variables || "[]",
427
+ template.description,
428
+ template.is_active || 1,
429
+ now,
430
+ now,
431
+ userId
432
+ ).run();
433
+ }
434
+ if (this.cache) {
435
+ await this.cache.putTemplate(template);
436
+ }
437
+ }
438
+ async deleteTemplate(templateId) {
439
+ const table = `${this.config.emailTablePrefix}templates`;
440
+ await this.db.prepare(`DELETE FROM ${table} WHERE template_id = ?`).bind(templateId).run();
441
+ if (this.cache) {
442
+ await this.cache.deleteTemplate(templateId);
443
+ }
444
+ }
445
+ // --- Rendering ---
446
+ async renderTemplate(templateId, data) {
447
+ const template = await this.getTemplate(templateId);
448
+ if (!template) throw new Error(`Template not found: ${templateId}`);
449
+ const subject = Mustache.render(template.subject_template, data);
450
+ const markdown = Mustache.render(template.body_markdown, data);
451
+ marked.use({ mangle: false, headerIds: false });
452
+ const htmlContent = marked.parse(markdown);
453
+ const html = this.wrapInBaseTemplate(htmlContent, subject, data);
454
+ const plainText = markdown.replace(/<[^>]*>/g, "");
455
+ return { subject, html, plainText };
456
+ }
457
+ wrapInBaseTemplate(content, subject, data = {}) {
458
+ const templateData = {
459
+ ...data,
460
+ brandName: data.brandName || this.config.branding.brandName,
461
+ portalUrl: data.portalUrl || this.config.branding.portalUrl,
462
+ unsubscribeUrl: data.unsubscribeUrl || "{{unsubscribe_url}}"
463
+ };
464
+ return wrapInEmailTemplate(content, subject, templateData);
465
+ }
466
+ // --- Delivery ---
467
+ /**
468
+ * Send a single email
469
+ * @param {Object} params - Email parameters
470
+ * @param {string} params.to - Recipient email
471
+ * @param {string} params.subject - Email subject
472
+ * @param {string} params.html - HTML body
473
+ * @param {string} params.text - Plain text body
474
+ * @param {string} [params.provider] - Override provider
475
+ * @param {string} [params.profile='system'] - 'system' or 'tenant'
476
+ * @param {string} [params.tenantId] - Required if profile is 'tenant'
477
+ * @param {Object} [params.metadata] - Additional metadata
478
+ * @returns {Promise<Object>} Delivery result
479
+ */
480
+ async sendEmail({ to, subject, html, htmlBody, text, textBody, provider, profile = "system", tenantId = null, metadata = {} }) {
481
+ const htmlContent = html || htmlBody;
482
+ const textContent = text || textBody;
483
+ try {
484
+ const settings = await this.loadSettings(profile, tenantId);
485
+ const useProvider = provider || settings.provider || "mailchannels";
486
+ let result;
487
+ switch (useProvider) {
488
+ case "mailchannels":
489
+ result = await this.sendViaMailChannels(to, subject, htmlContent, textContent, settings, metadata);
490
+ break;
491
+ case "sendgrid":
492
+ result = await this.sendViaSendGrid(to, subject, htmlContent, textContent, settings, metadata);
493
+ break;
494
+ case "resend":
495
+ result = await this.sendViaResend(to, subject, htmlContent, textContent, settings, metadata);
496
+ break;
497
+ case "sendpulse":
498
+ result = await this.sendViaSendPulse(to, subject, htmlContent, textContent, settings, metadata);
499
+ break;
500
+ default:
501
+ console.error(`[EmailService] Unknown provider: ${useProvider}`);
502
+ return { success: false, error: `Unknown email provider: ${useProvider}` };
503
+ }
504
+ if (result) {
505
+ return { success: true, messageId: crypto.randomUUID() };
506
+ } else {
507
+ console.error("[EmailService] Failed to send email to:", to);
508
+ return { success: false, error: "Failed to send email" };
509
+ }
510
+ } catch (error) {
511
+ console.error("[EmailService] Error sending email:", error);
512
+ return { success: false, error: error.message };
513
+ }
514
+ }
515
+ /**
516
+ * Send multiple emails in batch
517
+ * @param {Array} emails - Array of email objects
518
+ * @returns {Promise<Array>} Array of delivery results
519
+ */
520
+ async sendBatch(emails) {
521
+ console.log("[EmailService] Sending batch of", emails.length, "emails");
522
+ const results = await Promise.all(
523
+ emails.map((email) => this.sendEmail(email))
524
+ );
525
+ return results;
526
+ }
527
+ /**
528
+ * Send email via MailChannels HTTP API
529
+ * MailChannels is specifically designed for Cloudflare Workers
530
+ */
531
+ async sendViaMailChannels(to, subject, html, text, settings, metadata) {
532
+ try {
533
+ const response = await fetch("https://api.mailchannels.net/tx/v1/send", {
534
+ method: "POST",
535
+ headers: { "Content-Type": "application/json" },
536
+ body: JSON.stringify({
537
+ personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
538
+ from: { email: settings.fromAddress, name: settings.fromName },
539
+ subject,
540
+ content: [
541
+ { type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") },
542
+ { type: "text/html", value: html }
543
+ ]
544
+ })
545
+ });
546
+ if (response.status === 202) {
547
+ return true;
548
+ } else {
549
+ const contentType = response.headers.get("content-type");
550
+ const errorBody = (contentType == null ? void 0 : contentType.includes("application/json")) ? await response.json() : await response.text();
551
+ console.error("[EmailService] MailChannels error:", response.status, errorBody);
552
+ return false;
553
+ }
554
+ } catch (error) {
555
+ console.error("[EmailService] MailChannels exception:", error.message);
556
+ return false;
557
+ }
558
+ }
559
+ /**
560
+ * Send email via SendGrid HTTP API
561
+ */
562
+ async sendViaSendGrid(to, subject, html, text, settings, metadata) {
563
+ try {
564
+ if (!settings.sendgridApiKey) {
565
+ console.error("[EmailService] SendGrid API key missing");
566
+ return false;
567
+ }
568
+ const response = await fetch("https://api.sendgrid.com/v3/mail/send", {
569
+ method: "POST",
570
+ headers: {
571
+ "Authorization": `Bearer ${settings.sendgridApiKey}`,
572
+ "Content-Type": "application/json"
573
+ },
574
+ body: JSON.stringify({
575
+ personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
576
+ from: { email: settings.fromAddress, name: settings.fromName },
577
+ subject,
578
+ content: [
579
+ { type: "text/html", value: html },
580
+ { type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") }
581
+ ]
582
+ })
583
+ });
584
+ if (response.status === 202) {
585
+ return true;
586
+ } else {
587
+ const errorText = await response.text();
588
+ console.error("[EmailService] SendGrid error:", response.status, errorText);
589
+ return false;
590
+ }
591
+ } catch (error) {
592
+ console.error("[EmailService] SendGrid exception:", error.message);
593
+ return false;
594
+ }
595
+ }
596
+ /**
597
+ * Send email via Resend HTTP API
598
+ */
599
+ async sendViaResend(to, subject, html, text, settings, metadata) {
600
+ try {
601
+ if (!settings.resendApiKey) {
602
+ console.error("[EmailService] Resend API key missing");
603
+ return false;
604
+ }
605
+ const response = await fetch("https://api.resend.com/emails", {
606
+ method: "POST",
607
+ headers: {
608
+ "Authorization": `Bearer ${settings.resendApiKey}`,
609
+ "Content-Type": "application/json"
610
+ },
611
+ body: JSON.stringify({
612
+ from: `${settings.fromName} <${settings.fromAddress}>`,
613
+ to: [to],
614
+ subject,
615
+ html,
616
+ text: text || html.replace(/<[^>]*>/g, "")
617
+ })
618
+ });
619
+ if (response.ok) {
620
+ return true;
621
+ } else {
622
+ const errorText = await response.text();
623
+ console.error("[EmailService] Resend error:", response.status, errorText);
624
+ return false;
625
+ }
626
+ } catch (error) {
627
+ console.error("[EmailService] Resend exception:", error.message);
628
+ return false;
629
+ }
630
+ }
631
+ /**
632
+ * Send email via SendPulse HTTP API
633
+ * SendPulse offers 15,000 free emails/month
634
+ */
635
+ async sendViaSendPulse(to, subject, html, text, settings, metadata) {
636
+ try {
637
+ if (!settings.sendpulseClientId || !settings.sendpulseClientSecret) {
638
+ console.error("[EmailService] SendPulse credentials missing");
639
+ return false;
640
+ }
641
+ const tokenParams = new URLSearchParams({
642
+ grant_type: "client_credentials",
643
+ client_id: settings.sendpulseClientId,
644
+ client_secret: settings.sendpulseClientSecret
645
+ });
646
+ const tokenResponse = await fetch("https://api.sendpulse.com/oauth/access_token", {
647
+ method: "POST",
648
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
649
+ body: tokenParams.toString()
650
+ });
651
+ if (!tokenResponse.ok) {
652
+ const error = await tokenResponse.text();
653
+ console.error("[EmailService] SendPulse auth error:", error);
654
+ return false;
655
+ }
656
+ const tokenData = await tokenResponse.json();
657
+ if (!tokenData.access_token) {
658
+ console.error("[EmailService] SendPulse: No access token in response");
659
+ return false;
660
+ }
661
+ const { access_token } = tokenData;
662
+ const toBase64 = (str) => {
663
+ if (!str) return "";
664
+ return Buffer.from(String(str)).toString("base64");
665
+ };
666
+ const htmlSafe = html || "";
667
+ const textSafe = text || (htmlSafe ? htmlSafe.replace(/<[^>]*>/g, "") : "");
668
+ const response = await fetch("https://api.sendpulse.com/smtp/emails", {
669
+ method: "POST",
670
+ headers: {
671
+ "Authorization": `Bearer ${access_token}`,
672
+ "Content-Type": "application/json"
673
+ },
674
+ body: JSON.stringify({
675
+ email: {
676
+ html: toBase64(htmlSafe),
677
+ text: toBase64(textSafe),
678
+ subject,
679
+ from: { name: settings.fromName, email: settings.fromAddress },
680
+ to: [{ name: metadata.recipientName || "", email: to }]
681
+ }
682
+ })
683
+ });
684
+ if (response.ok) {
685
+ return true;
686
+ } else {
687
+ const errorText = await response.text();
688
+ console.error("[EmailService] SendPulse send error:", response.status, errorText);
689
+ return false;
690
+ }
691
+ } catch (error) {
692
+ console.error("[EmailService] SendPulse exception:", error.message);
693
+ return false;
694
+ }
695
+ }
696
+ };
697
+
698
+ // src/backend/routes/templates.js
699
+ function createTemplateRoutes(env, config = {}, cacheProvider = null) {
700
+ const app = new Hono();
701
+ const emailService = new EmailService(env, config, cacheProvider);
702
+ app.get("/templates", async (c) => {
703
+ try {
704
+ const templates = await emailService.getAllTemplates();
705
+ return c.json({ success: true, templates });
706
+ } catch (err) {
707
+ return c.json({ success: false, error: err.message }, 500);
708
+ }
709
+ });
710
+ app.get("/templates/:id", async (c) => {
711
+ try {
712
+ const template = await emailService.getTemplate(c.req.param("id"));
713
+ if (!template) return c.json({ success: false, error: "Template not found" }, 404);
714
+ return c.json({ success: true, template });
715
+ } catch (err) {
716
+ return c.json({ success: false, error: err.message }, 500);
717
+ }
718
+ });
719
+ app.post("/templates", async (c) => {
720
+ try {
721
+ const data = await c.req.json();
722
+ await emailService.saveTemplate(data, "admin");
723
+ return c.json({ success: true, message: "Template saved" });
724
+ } catch (err) {
725
+ return c.json({ success: false, error: err.message }, 500);
726
+ }
727
+ });
728
+ app.delete("/templates/:id", async (c) => {
729
+ try {
730
+ await emailService.deleteTemplate(c.req.param("id"));
731
+ return c.json({ success: true, message: "Template deleted" });
732
+ } catch (err) {
733
+ return c.json({ success: false, error: err.message }, 500);
734
+ }
735
+ });
736
+ app.post("/templates/:id/preview", async (c) => {
737
+ try {
738
+ const id = c.req.param("id");
739
+ const data = await c.req.json();
740
+ const result = await emailService.renderTemplate(id, data);
741
+ return c.json({ success: true, preview: result });
742
+ } catch (err) {
743
+ return c.json({ success: false, error: err.message }, 500);
744
+ }
745
+ });
746
+ app.post("/templates/:id/test", async (c) => {
747
+ try {
748
+ const id = c.req.param("id");
749
+ const { to, data } = await c.req.json();
750
+ const { subject, html, plainText } = await emailService.renderTemplate(id, data);
751
+ const result = await emailService.sendEmail({
752
+ to,
753
+ subject: `[TEST] ${subject}`,
754
+ html,
755
+ text: plainText
756
+ });
757
+ if (result.success) {
758
+ return c.json({ success: true, message: "Test email sent" });
759
+ } else {
760
+ return c.json({ success: false, error: result.error }, 500);
761
+ }
762
+ } catch (err) {
763
+ return c.json({ success: false, error: err.message }, 500);
764
+ }
765
+ });
766
+ return app;
767
+ }
768
+
769
+ // src/backend/routes/tracking.js
770
+ import { Hono as Hono2 } from "hono";
771
+ var TRACKING_PIXEL = new Uint8Array([
772
+ 71,
773
+ 73,
774
+ 70,
775
+ 56,
776
+ 57,
777
+ 97,
778
+ 1,
779
+ 0,
780
+ 1,
781
+ 0,
782
+ 128,
783
+ 0,
784
+ 0,
785
+ 0,
786
+ 0,
787
+ 0,
788
+ 255,
789
+ 255,
790
+ 255,
791
+ 33,
792
+ 249,
793
+ 4,
794
+ 1,
795
+ 0,
796
+ 0,
797
+ 0,
798
+ 0,
799
+ 44,
800
+ 0,
801
+ 0,
802
+ 0,
803
+ 0,
804
+ 1,
805
+ 0,
806
+ 1,
807
+ 0,
808
+ 0,
809
+ 2,
810
+ 1,
811
+ 68,
812
+ 0,
813
+ 59
814
+ ]);
815
+ function createTrackingRoutes(env, config = {}) {
816
+ const app = new Hono2();
817
+ const db = env.DB;
818
+ const tablePrefix = config.emailTablePrefix || config.tableNamePrefix || "system_email_";
819
+ app.get("/track/open/:token", async (c) => {
820
+ const token = c.req.param("token");
821
+ try {
822
+ const sendId = token;
823
+ const send = await db.prepare(`SELECT * FROM ${tablePrefix}sends WHERE send_id = ?`).bind(sendId).first();
824
+ if (send) {
825
+ const eventId = crypto.randomUUID();
826
+ const now = Math.floor(Date.now() / 1e3);
827
+ await db.prepare(
828
+ `INSERT INTO ${tablePrefix}events (
829
+ event_id, send_id, user_id, tenant_id, email_kind, event_type, metadata, created_at
830
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
831
+ ).bind(
832
+ eventId,
833
+ sendId,
834
+ send.user_id,
835
+ send.tenant_id,
836
+ send.email_kind,
837
+ "opened",
838
+ JSON.stringify({
839
+ user_agent: c.req.header("user-agent"),
840
+ referer: c.req.header("referer")
841
+ }),
842
+ now
843
+ ).run();
844
+ }
845
+ } catch (error) {
846
+ console.error("[EmailTracking] Error tracking email open:", error);
847
+ }
848
+ return new Response(TRACKING_PIXEL, {
849
+ headers: {
850
+ "Content-Type": "image/gif",
851
+ "Cache-Control": "no-cache, no-store, must-revalidate",
852
+ "Pragma": "no-cache",
853
+ "Expires": "0"
854
+ }
855
+ });
856
+ });
857
+ app.post("/track/click/:token", async (c) => {
858
+ const token = c.req.param("token");
859
+ let url;
860
+ try {
861
+ const body = await c.req.json();
862
+ url = body.url;
863
+ } catch {
864
+ return c.json({ success: false, error: "Invalid request body" }, 400);
865
+ }
866
+ if (!url) {
867
+ return c.json({ success: false, error: "Missing URL" }, 400);
868
+ }
869
+ try {
870
+ const sendId = token;
871
+ const send = await db.prepare(`SELECT * FROM ${tablePrefix}sends WHERE send_id = ?`).bind(sendId).first();
872
+ if (send) {
873
+ const eventId = crypto.randomUUID();
874
+ const now = Math.floor(Date.now() / 1e3);
875
+ await db.prepare(
876
+ `INSERT INTO ${tablePrefix}events (
877
+ event_id, send_id, user_id, tenant_id, email_kind, event_type, metadata, created_at
878
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
879
+ ).bind(
880
+ eventId,
881
+ sendId,
882
+ send.user_id,
883
+ send.tenant_id,
884
+ send.email_kind,
885
+ "clicked",
886
+ JSON.stringify({
887
+ url,
888
+ user_agent: c.req.header("user-agent"),
889
+ referer: c.req.header("referer")
890
+ }),
891
+ now
892
+ ).run();
893
+ }
894
+ return c.json({ success: true, tracked: !!send });
895
+ } catch (error) {
896
+ console.error("[EmailTracking] Error tracking email click:", error);
897
+ return c.json({ success: false, error: "Failed to track click" }, 500);
898
+ }
899
+ });
900
+ app.get("/unsubscribe/:token", async (c) => {
901
+ const unsubToken = c.req.param("token");
902
+ try {
903
+ const prefs = await db.prepare(`SELECT * FROM ${tablePrefix}preferences WHERE unsub_token = ?`).bind(unsubToken).first();
904
+ if (!prefs) {
905
+ return c.json({ success: false, error: "Invalid unsubscribe link" }, 404);
906
+ }
907
+ const currentSettings = JSON.parse(prefs.email_settings || "{}");
908
+ const alreadyUnsubscribed = Object.keys(currentSettings).length === 0;
909
+ if (!alreadyUnsubscribed) {
910
+ const now = Math.floor(Date.now() / 1e3);
911
+ await db.prepare(
912
+ `UPDATE ${tablePrefix}preferences
913
+ SET email_settings = '{}',
914
+ updated_at = ?
915
+ WHERE unsub_token = ?`
916
+ ).bind(now, unsubToken).run();
917
+ const eventId = crypto.randomUUID();
918
+ await db.prepare(
919
+ `INSERT INTO ${tablePrefix}events (
920
+ event_id, send_id, user_id, tenant_id, email_kind, event_type, metadata, created_at
921
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
922
+ ).bind(
923
+ eventId,
924
+ "unsubscribe",
925
+ prefs.user_id,
926
+ prefs.tenant_id,
927
+ "all",
928
+ "unsubscribed",
929
+ JSON.stringify({
930
+ user_agent: c.req.header("user-agent")
931
+ }),
932
+ now
933
+ ).run();
934
+ }
935
+ return c.json({ success: true, alreadyUnsubscribed });
936
+ } catch (error) {
937
+ console.error("[EmailTracking] Error processing unsubscribe:", error);
938
+ return c.json({ success: false, error: "An error occurred" }, 500);
939
+ }
940
+ });
941
+ return app;
942
+ }
943
+
944
+ // src/backend/routes/index.js
945
+ function createEmailRoutes(env, config = {}, cacheProvider = null) {
946
+ const app = new Hono3();
947
+ app.route("/api/email", createTemplateRoutes(env, config, cacheProvider));
948
+ app.route("/email", createTrackingRoutes(env, config));
949
+ return app;
950
+ }
951
+ export {
952
+ createEmailRoutes,
953
+ createTemplateRoutes,
954
+ createTrackingRoutes
955
+ };
956
+ //# sourceMappingURL=index.js.map