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