@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.
- package/dist/backend/EmailService.cjs +728 -0
- package/dist/backend/EmailService.cjs.map +1 -0
- package/dist/backend/EmailService.js +694 -0
- package/dist/backend/EmailService.js.map +1 -0
- package/dist/backend/EmailingCacheDO.cjs +390 -0
- package/dist/backend/EmailingCacheDO.cjs.map +1 -0
- package/dist/backend/EmailingCacheDO.js +365 -0
- package/dist/backend/EmailingCacheDO.js.map +1 -0
- package/dist/backend/routes/index.cjs +992 -0
- package/dist/backend/routes/index.cjs.map +1 -0
- package/dist/backend/routes/index.js +956 -0
- package/dist/backend/routes/index.js.map +1 -0
- package/dist/cli.cjs +53 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.js +53 -0
- package/dist/cli.js.map +1 -0
- package/dist/common/index.cjs +267 -0
- package/dist/common/index.cjs.map +1 -0
- package/{src/common/htmlWrapper.js → dist/common/index.js} +75 -18
- package/dist/common/index.js.map +1 -0
- package/dist/index.cjs +1537 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +1488 -0
- package/dist/index.js.map +1 -0
- package/package.json +27 -12
- package/examples/.env.example +0 -16
- package/examples/README.md +0 -55
- package/examples/mocks/MockD1.js +0 -311
- package/examples/mocks/MockEmailSender.js +0 -64
- package/examples/mocks/index.js +0 -5
- package/examples/package-lock.json +0 -73
- package/examples/package.json +0 -18
- package/examples/portal/index.html +0 -919
- package/examples/server.js +0 -314
- package/release.sh +0 -56
- package/src/backend/EmailService.js +0 -537
- package/src/backend/EmailingCacheDO.js +0 -466
- package/src/backend/routes/index.js +0 -30
- package/src/backend/routes/templates.js +0 -98
- package/src/backend/routes/tracking.js +0 -215
- package/src/backend/routes.js +0 -98
- package/src/common/index.js +0 -11
- package/src/common/utils.js +0 -141
- package/src/frontend/TemplateEditor.jsx +0 -117
- package/src/frontend/TemplateManager.jsx +0 -117
- package/src/index.js +0 -24
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1537 @@
|
|
|
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/index.js
|
|
30
|
+
var index_exports = {};
|
|
31
|
+
__export(index_exports, {
|
|
32
|
+
EmailService: () => EmailService,
|
|
33
|
+
EmailingCacheDO: () => EmailingCacheDO,
|
|
34
|
+
TemplateEditor: () => TemplateEditor,
|
|
35
|
+
TemplateManager: () => TemplateManager,
|
|
36
|
+
createDOCacheProvider: () => createDOCacheProvider,
|
|
37
|
+
createEmailRoutes: () => createEmailRoutes,
|
|
38
|
+
createTemplateRoutes: () => createTemplateRoutes,
|
|
39
|
+
createTrackingRoutes: () => createTrackingRoutes,
|
|
40
|
+
encodeTrackingLinks: () => encodeTrackingLinks,
|
|
41
|
+
extractVariables: () => extractVariables,
|
|
42
|
+
getWebsiteUrl: () => getWebsiteUrl,
|
|
43
|
+
markdownToPlainText: () => markdownToPlainText,
|
|
44
|
+
resetWebsiteUrlCache: () => resetWebsiteUrlCache,
|
|
45
|
+
wrapInEmailTemplate: () => wrapInEmailTemplate
|
|
46
|
+
});
|
|
47
|
+
module.exports = __toCommonJS(index_exports);
|
|
48
|
+
|
|
49
|
+
// src/backend/EmailService.js
|
|
50
|
+
var import_marked = require("marked");
|
|
51
|
+
var import_mustache = __toESM(require("mustache"), 1);
|
|
52
|
+
|
|
53
|
+
// src/common/htmlWrapper.js
|
|
54
|
+
function wrapInEmailTemplate(contentHtml, subject, data = {}) {
|
|
55
|
+
const portalUrl = data.portalUrl || "https://app.x0start.com";
|
|
56
|
+
const unsubscribeUrl = data.unsubscribeUrl || "{{unsubscribe_url}}";
|
|
57
|
+
const brandName = data.brandName || "X0 Start";
|
|
58
|
+
return `
|
|
59
|
+
<!DOCTYPE html>
|
|
60
|
+
<html lang="en">
|
|
61
|
+
<head>
|
|
62
|
+
<meta charset="UTF-8">
|
|
63
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
64
|
+
<title>${subject}</title>
|
|
65
|
+
<style>
|
|
66
|
+
body {
|
|
67
|
+
margin: 0;
|
|
68
|
+
padding: 0;
|
|
69
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
|
70
|
+
background-color: #f5f5f5;
|
|
71
|
+
line-height: 1.6;
|
|
72
|
+
}
|
|
73
|
+
.email-wrapper {
|
|
74
|
+
background-color: #f5f5f5;
|
|
75
|
+
padding: 40px 20px;
|
|
76
|
+
}
|
|
77
|
+
.email-container {
|
|
78
|
+
max-width: 600px;
|
|
79
|
+
margin: 0 auto;
|
|
80
|
+
background-color: #ffffff;
|
|
81
|
+
border-radius: 8px;
|
|
82
|
+
overflow: hidden;
|
|
83
|
+
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
|
84
|
+
}
|
|
85
|
+
.email-header {
|
|
86
|
+
padding: 40px 40px 20px;
|
|
87
|
+
text-align: center;
|
|
88
|
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
|
89
|
+
color: #ffffff;
|
|
90
|
+
}
|
|
91
|
+
.email-header h1 {
|
|
92
|
+
margin: 0;
|
|
93
|
+
font-size: 28px;
|
|
94
|
+
font-weight: 600;
|
|
95
|
+
}
|
|
96
|
+
.email-content {
|
|
97
|
+
padding: 30px 40px;
|
|
98
|
+
color: #333333;
|
|
99
|
+
}
|
|
100
|
+
.email-content h1 {
|
|
101
|
+
font-size: 24px;
|
|
102
|
+
margin-top: 0;
|
|
103
|
+
margin-bottom: 20px;
|
|
104
|
+
color: #333333;
|
|
105
|
+
}
|
|
106
|
+
.email-content h2 {
|
|
107
|
+
font-size: 20px;
|
|
108
|
+
margin-top: 30px;
|
|
109
|
+
margin-bottom: 15px;
|
|
110
|
+
color: #333333;
|
|
111
|
+
}
|
|
112
|
+
.email-content h3 {
|
|
113
|
+
font-size: 16px;
|
|
114
|
+
margin-top: 20px;
|
|
115
|
+
margin-bottom: 10px;
|
|
116
|
+
color: #333333;
|
|
117
|
+
}
|
|
118
|
+
.email-content p {
|
|
119
|
+
margin: 0 0 15px;
|
|
120
|
+
color: #666666;
|
|
121
|
+
}
|
|
122
|
+
.email-content a {
|
|
123
|
+
color: #667eea;
|
|
124
|
+
text-decoration: none;
|
|
125
|
+
}
|
|
126
|
+
.email-content ul, .email-content ol {
|
|
127
|
+
margin: 0 0 15px;
|
|
128
|
+
padding-left: 25px;
|
|
129
|
+
}
|
|
130
|
+
.email-content li {
|
|
131
|
+
margin-bottom: 8px;
|
|
132
|
+
color: #666666;
|
|
133
|
+
}
|
|
134
|
+
.email-content blockquote {
|
|
135
|
+
margin: 20px 0;
|
|
136
|
+
padding: 15px 20px;
|
|
137
|
+
background-color: #f8f9fa;
|
|
138
|
+
border-left: 4px solid #667eea;
|
|
139
|
+
color: #666666;
|
|
140
|
+
}
|
|
141
|
+
.email-content code {
|
|
142
|
+
padding: 2px 6px;
|
|
143
|
+
background-color: #f8f9fa;
|
|
144
|
+
border-radius: 3px;
|
|
145
|
+
font-family: 'Courier New', monospace;
|
|
146
|
+
font-size: 14px;
|
|
147
|
+
}
|
|
148
|
+
.email-content pre {
|
|
149
|
+
padding: 15px;
|
|
150
|
+
background-color: #f8f9fa;
|
|
151
|
+
border-radius: 6px;
|
|
152
|
+
overflow-x: auto;
|
|
153
|
+
}
|
|
154
|
+
.email-content pre code {
|
|
155
|
+
padding: 0;
|
|
156
|
+
background: none;
|
|
157
|
+
}
|
|
158
|
+
.btn {
|
|
159
|
+
display: inline-block;
|
|
160
|
+
padding: 12px 24px;
|
|
161
|
+
background-color: #667eea;
|
|
162
|
+
color: #ffffff !important;
|
|
163
|
+
text-decoration: none;
|
|
164
|
+
border-radius: 6px;
|
|
165
|
+
font-weight: 600;
|
|
166
|
+
margin: 10px 0;
|
|
167
|
+
}
|
|
168
|
+
.btn:hover {
|
|
169
|
+
background-color: #5568d3;
|
|
170
|
+
}
|
|
171
|
+
.email-footer {
|
|
172
|
+
padding: 20px 40px;
|
|
173
|
+
background-color: #f8f9fa;
|
|
174
|
+
text-align: center;
|
|
175
|
+
font-size: 12px;
|
|
176
|
+
color: #666666;
|
|
177
|
+
}
|
|
178
|
+
.email-footer a {
|
|
179
|
+
color: #667eea;
|
|
180
|
+
text-decoration: none;
|
|
181
|
+
}
|
|
182
|
+
hr {
|
|
183
|
+
border: none;
|
|
184
|
+
border-top: 1px solid #e0e0e0;
|
|
185
|
+
margin: 30px 0;
|
|
186
|
+
}
|
|
187
|
+
</style>
|
|
188
|
+
</head>
|
|
189
|
+
<body>
|
|
190
|
+
<div class="email-wrapper">
|
|
191
|
+
<div class="email-container">
|
|
192
|
+
<div class="email-content">
|
|
193
|
+
${contentHtml}
|
|
194
|
+
</div>
|
|
195
|
+
<div class="email-footer">
|
|
196
|
+
<p style="margin: 0 0 10px;">
|
|
197
|
+
You're receiving this email from ${brandName}.
|
|
198
|
+
</p>
|
|
199
|
+
<p style="margin: 0;">
|
|
200
|
+
<a href="${unsubscribeUrl}">Unsubscribe</a> |
|
|
201
|
+
<a href="${portalUrl}/settings/notifications">Manage Preferences</a>
|
|
202
|
+
</p>
|
|
203
|
+
</div>
|
|
204
|
+
</div>
|
|
205
|
+
</div>
|
|
206
|
+
</body>
|
|
207
|
+
</html>
|
|
208
|
+
`.trim();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/backend/EmailingCacheDO.js
|
|
212
|
+
var EmailingCacheDO = class {
|
|
213
|
+
constructor(state, env) {
|
|
214
|
+
this.state = state;
|
|
215
|
+
this.env = env;
|
|
216
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
217
|
+
this.settingsCache = /* @__PURE__ */ new Map();
|
|
218
|
+
this.cacheTTL = 36e5;
|
|
219
|
+
this.emailTablePrefix = env.EMAIL_TABLE_PREFIX || "system_email_";
|
|
220
|
+
this.settingsTableName = env.EMAIL_SETTINGS_TABLE || "system_settings";
|
|
221
|
+
this.settingsKeyPrefix = env.EMAIL_SETTINGS_KEY_PREFIX || "";
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Handle HTTP requests to this Durable Object
|
|
225
|
+
*/
|
|
226
|
+
async fetch(request) {
|
|
227
|
+
const url = new URL(request.url);
|
|
228
|
+
const path = url.pathname;
|
|
229
|
+
try {
|
|
230
|
+
if (path === "/get" && request.method === "GET") {
|
|
231
|
+
return this.handleGet(request);
|
|
232
|
+
} else if (path === "/invalidate" && request.method === "POST") {
|
|
233
|
+
return this.handleInvalidate(request);
|
|
234
|
+
} else if (path === "/clear" && request.method === "POST") {
|
|
235
|
+
return this.handleClear(request);
|
|
236
|
+
} else if (path === "/stats" && request.method === "GET") {
|
|
237
|
+
return this.handleStats(request);
|
|
238
|
+
} else if (path === "/settings/get" && request.method === "GET") {
|
|
239
|
+
return this.handleGetSettings(request);
|
|
240
|
+
} else if (path === "/settings/put" && request.method === "POST") {
|
|
241
|
+
return this.handlePutSettings(request);
|
|
242
|
+
} else if (path === "/settings/invalidate" && request.method === "POST") {
|
|
243
|
+
return this.handleInvalidateSettings(request);
|
|
244
|
+
} else {
|
|
245
|
+
return new Response("Not Found", { status: 404 });
|
|
246
|
+
}
|
|
247
|
+
} catch (error) {
|
|
248
|
+
console.error("[EmailingCacheDO] Error:", error);
|
|
249
|
+
return new Response(JSON.stringify({ error: error.message }), {
|
|
250
|
+
status: 500,
|
|
251
|
+
headers: { "Content-Type": "application/json" }
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Get template (from cache or D1)
|
|
257
|
+
*/
|
|
258
|
+
async handleGet(request) {
|
|
259
|
+
const url = new URL(request.url);
|
|
260
|
+
const templateId = url.searchParams.get("templateId");
|
|
261
|
+
const forceRefresh = url.searchParams.get("refresh") === "true";
|
|
262
|
+
if (!templateId) {
|
|
263
|
+
return new Response(JSON.stringify({ error: "templateId is required" }), {
|
|
264
|
+
status: 400,
|
|
265
|
+
headers: { "Content-Type": "application/json" }
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
if (!forceRefresh) {
|
|
269
|
+
const cached = this.cache.get(templateId);
|
|
270
|
+
if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
|
|
271
|
+
console.log("[EmailingCacheDO] Cache HIT:", templateId);
|
|
272
|
+
return new Response(JSON.stringify({
|
|
273
|
+
template: cached.data,
|
|
274
|
+
cached: true,
|
|
275
|
+
age: Date.now() - cached.timestamp
|
|
276
|
+
}), {
|
|
277
|
+
headers: { "Content-Type": "application/json" }
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
console.log("[EmailingCacheDO] Cache MISS - fetching from D1:", templateId);
|
|
282
|
+
const template = await this.fetchTemplateFromD1(templateId);
|
|
283
|
+
if (!template) {
|
|
284
|
+
return new Response(JSON.stringify({
|
|
285
|
+
error: "Template not found",
|
|
286
|
+
templateId
|
|
287
|
+
}), {
|
|
288
|
+
status: 404,
|
|
289
|
+
headers: { "Content-Type": "application/json" }
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
this.cache.set(templateId, {
|
|
293
|
+
data: template,
|
|
294
|
+
timestamp: Date.now()
|
|
295
|
+
});
|
|
296
|
+
return new Response(JSON.stringify({
|
|
297
|
+
template,
|
|
298
|
+
cached: false
|
|
299
|
+
}), {
|
|
300
|
+
headers: { "Content-Type": "application/json" }
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
// --- Settings Cache Handlers ---
|
|
304
|
+
async handleGetSettings(request) {
|
|
305
|
+
const url = new URL(request.url);
|
|
306
|
+
const key = url.searchParams.get("key");
|
|
307
|
+
if (!key) return new Response("Key required", { status: 400 });
|
|
308
|
+
const cached = this.settingsCache.get(key);
|
|
309
|
+
if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
|
|
310
|
+
console.log("[EmailingCacheDO] Settings Cache HIT:", key);
|
|
311
|
+
return new Response(JSON.stringify({ settings: cached.data }), {
|
|
312
|
+
headers: { "Content-Type": "application/json" }
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
if (key.startsWith("system")) {
|
|
316
|
+
console.log("[EmailingCacheDO] Settings Cache MISS - fetching from D1:", key);
|
|
317
|
+
const settings = await this.fetchSettingsFromD1(key);
|
|
318
|
+
if (settings) {
|
|
319
|
+
this.settingsCache.set(key, {
|
|
320
|
+
data: settings,
|
|
321
|
+
timestamp: Date.now()
|
|
322
|
+
});
|
|
323
|
+
return new Response(JSON.stringify({ settings }), {
|
|
324
|
+
headers: { "Content-Type": "application/json" }
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return new Response(JSON.stringify({ settings: null }), {
|
|
329
|
+
headers: { "Content-Type": "application/json" }
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
async handlePutSettings(request) {
|
|
333
|
+
try {
|
|
334
|
+
const body = await request.json();
|
|
335
|
+
const { key, settings } = body;
|
|
336
|
+
if (!key || !settings) return new Response("Key and settings required", { status: 400 });
|
|
337
|
+
this.settingsCache.set(key, {
|
|
338
|
+
data: settings,
|
|
339
|
+
timestamp: Date.now()
|
|
340
|
+
});
|
|
341
|
+
if (key.startsWith("system")) {
|
|
342
|
+
await this.saveSettingsToD1(settings);
|
|
343
|
+
}
|
|
344
|
+
return new Response(JSON.stringify({ success: true }), {
|
|
345
|
+
headers: { "Content-Type": "application/json" }
|
|
346
|
+
});
|
|
347
|
+
} catch (e) {
|
|
348
|
+
console.error("[EmailingCacheDO] PutSettings error:", e);
|
|
349
|
+
return new Response("Error parsing body/saving", { status: 400 });
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async handleInvalidateSettings(request) {
|
|
353
|
+
try {
|
|
354
|
+
const body = await request.json();
|
|
355
|
+
const { key } = body;
|
|
356
|
+
if (!key) return new Response("Key required", { status: 400 });
|
|
357
|
+
const existed = this.settingsCache.has(key);
|
|
358
|
+
this.settingsCache.delete(key);
|
|
359
|
+
console.log("[EmailingCacheDO] Invalidated settings:", key, existed ? "(existed)" : "(not in cache)");
|
|
360
|
+
return new Response(JSON.stringify({ success: true, existed }), {
|
|
361
|
+
headers: { "Content-Type": "application/json" }
|
|
362
|
+
});
|
|
363
|
+
} catch (e) {
|
|
364
|
+
console.error("[EmailingCacheDO] InvalidateSettings error:", e);
|
|
365
|
+
return new Response("Error invalidated settings", { status: 400 });
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Invalidate specific template(s) from cache
|
|
370
|
+
* Body: { templateId: 'template_id' } or { templateId: '*' } for all
|
|
371
|
+
*/
|
|
372
|
+
async handleInvalidate(request) {
|
|
373
|
+
const body = await request.json();
|
|
374
|
+
const { templateId } = body;
|
|
375
|
+
if (!templateId) {
|
|
376
|
+
return new Response(JSON.stringify({ error: "templateId is required" }), {
|
|
377
|
+
status: 400,
|
|
378
|
+
headers: { "Content-Type": "application/json" }
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
if (templateId === "*") {
|
|
382
|
+
const count = this.cache.size;
|
|
383
|
+
this.cache.clear();
|
|
384
|
+
console.log("[EmailingCacheDO] Invalidated ALL templates:", count);
|
|
385
|
+
return new Response(JSON.stringify({
|
|
386
|
+
success: true,
|
|
387
|
+
message: `Invalidated ${count} templates`
|
|
388
|
+
}), {
|
|
389
|
+
headers: { "Content-Type": "application/json" }
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
const existed = this.cache.has(templateId);
|
|
393
|
+
this.cache.delete(templateId);
|
|
394
|
+
console.log("[EmailingCacheDO] Invalidated template:", templateId, existed ? "(existed)" : "(not in cache)");
|
|
395
|
+
return new Response(JSON.stringify({
|
|
396
|
+
success: true,
|
|
397
|
+
message: existed ? "Template invalidated" : "Template was not in cache",
|
|
398
|
+
templateId
|
|
399
|
+
}), {
|
|
400
|
+
headers: { "Content-Type": "application/json" }
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Clear entire cache (admin operation)
|
|
405
|
+
*/
|
|
406
|
+
async handleClear(request) {
|
|
407
|
+
const count = this.cache.size + this.settingsCache.size;
|
|
408
|
+
this.cache.clear();
|
|
409
|
+
this.settingsCache.clear();
|
|
410
|
+
console.log("[EmailingCacheDO] Cache cleared:", count, "entries (templates + settings)");
|
|
411
|
+
return new Response(JSON.stringify({
|
|
412
|
+
success: true,
|
|
413
|
+
message: `Cleared ${count} cached items`
|
|
414
|
+
}), {
|
|
415
|
+
headers: { "Content-Type": "application/json" }
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Get cache statistics
|
|
420
|
+
*/
|
|
421
|
+
async handleStats(request) {
|
|
422
|
+
const stats = {
|
|
423
|
+
templates: this.cache.size,
|
|
424
|
+
settings: this.settingsCache.size,
|
|
425
|
+
cacheTTL: this.cacheTTL
|
|
426
|
+
};
|
|
427
|
+
return new Response(JSON.stringify(stats), {
|
|
428
|
+
headers: { "Content-Type": "application/json" }
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Fetch template from D1
|
|
433
|
+
*/
|
|
434
|
+
async fetchTemplateFromD1(templateId) {
|
|
435
|
+
const db = this.env.DB;
|
|
436
|
+
const tableName = `${this.emailTablePrefix}templates`;
|
|
437
|
+
try {
|
|
438
|
+
const template = await db.prepare(`SELECT * FROM ${tableName} WHERE template_id = ? AND is_active = 1`).bind(templateId).first();
|
|
439
|
+
return template;
|
|
440
|
+
} catch (e) {
|
|
441
|
+
console.error(`[EmailingCacheDO] DB Error (${tableName}):`, e);
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Fetch settings from D1
|
|
447
|
+
* Only supports default table (e.g. system_settings) for now
|
|
448
|
+
*/
|
|
449
|
+
async fetchSettingsFromD1(key) {
|
|
450
|
+
const db = this.env.DB;
|
|
451
|
+
const tableName = this.settingsTableName;
|
|
452
|
+
const prefix = this.settingsKeyPrefix;
|
|
453
|
+
try {
|
|
454
|
+
let results;
|
|
455
|
+
if (prefix) {
|
|
456
|
+
try {
|
|
457
|
+
results = await db.prepare(`SELECT * FROM ${tableName} WHERE setting_key LIKE ?`).bind(`${prefix}%`).all();
|
|
458
|
+
} catch (e) {
|
|
459
|
+
results = await db.prepare(`SELECT * FROM ${tableName} WHERE key LIKE ?`).bind(`${prefix}%`).all();
|
|
460
|
+
}
|
|
461
|
+
} else {
|
|
462
|
+
results = await db.prepare(`SELECT * FROM ${tableName}`).all();
|
|
463
|
+
}
|
|
464
|
+
if (!results.results || results.results.length === 0) return null;
|
|
465
|
+
const settings = {};
|
|
466
|
+
results.results.forEach((row) => {
|
|
467
|
+
const k = row.setting_key || row.key;
|
|
468
|
+
const v = row.setting_value || row.value;
|
|
469
|
+
if (k) settings[k] = v;
|
|
470
|
+
});
|
|
471
|
+
return settings;
|
|
472
|
+
} catch (e) {
|
|
473
|
+
console.warn(`[EmailingCacheDO] Failed to load settings from ${tableName}:`, e);
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
async saveSettingsToD1(settings) {
|
|
478
|
+
const db = this.env.DB;
|
|
479
|
+
const tableName = this.settingsTableName;
|
|
480
|
+
const entries = Object.entries(settings);
|
|
481
|
+
for (const [k, v] of entries) {
|
|
482
|
+
try {
|
|
483
|
+
try {
|
|
484
|
+
const res = await db.prepare(`UPDATE ${tableName} SET setting_value = ? WHERE setting_key = ?`).bind(v, k).run();
|
|
485
|
+
if (res.meta.changes === 0) {
|
|
486
|
+
await db.prepare(`INSERT INTO ${tableName} (setting_key, setting_value) VALUES (?, ?)`).bind(k, v).run();
|
|
487
|
+
}
|
|
488
|
+
} catch (e) {
|
|
489
|
+
await db.prepare(`INSERT OR REPLACE INTO ${tableName} (key, value) VALUES (?, ?)`).bind(k, v).run();
|
|
490
|
+
}
|
|
491
|
+
} catch (e) {
|
|
492
|
+
console.warn("[EmailingCacheDO] Failed to save setting to D1:", k);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
function createDOCacheProvider(doStub, instanceName = "global") {
|
|
498
|
+
if (!doStub) {
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
const stub = doStub.get(doStub.idFromName(instanceName));
|
|
502
|
+
return {
|
|
503
|
+
async getTemplate(templateId) {
|
|
504
|
+
try {
|
|
505
|
+
const response = await stub.fetch(`http://do/get?templateId=${templateId}`);
|
|
506
|
+
const data = await response.json();
|
|
507
|
+
return data.template || null;
|
|
508
|
+
} catch (e) {
|
|
509
|
+
console.warn("[DOCacheProvider] Failed to get template:", e);
|
|
510
|
+
return null;
|
|
511
|
+
}
|
|
512
|
+
},
|
|
513
|
+
async getSettings(profile, tenantId) {
|
|
514
|
+
const key = `${profile}:${tenantId || ""}`;
|
|
515
|
+
try {
|
|
516
|
+
const response = await stub.fetch(`http://do/settings/get?key=${encodeURIComponent(key)}`);
|
|
517
|
+
const data = await response.json();
|
|
518
|
+
return data.settings || null;
|
|
519
|
+
} catch (e) {
|
|
520
|
+
return null;
|
|
521
|
+
}
|
|
522
|
+
},
|
|
523
|
+
async putSettings(profile, tenantId, settings) {
|
|
524
|
+
const key = `${profile}:${tenantId || ""}`;
|
|
525
|
+
try {
|
|
526
|
+
await stub.fetch("http://do/settings/put", {
|
|
527
|
+
method: "POST",
|
|
528
|
+
headers: { "Content-Type": "application/json" },
|
|
529
|
+
body: JSON.stringify({ key, settings })
|
|
530
|
+
});
|
|
531
|
+
} catch (e) {
|
|
532
|
+
console.warn("[DOCacheProvider] Failed to cache settings:", e);
|
|
533
|
+
}
|
|
534
|
+
},
|
|
535
|
+
async putTemplate(template) {
|
|
536
|
+
try {
|
|
537
|
+
await stub.fetch("http://do/invalidate", {
|
|
538
|
+
method: "POST",
|
|
539
|
+
headers: { "Content-Type": "application/json" },
|
|
540
|
+
body: JSON.stringify({ templateId: template.template_id })
|
|
541
|
+
});
|
|
542
|
+
} catch (e) {
|
|
543
|
+
console.warn("[DOCacheProvider] Failed to invalidate template:", e);
|
|
544
|
+
}
|
|
545
|
+
},
|
|
546
|
+
async deleteTemplate(templateId) {
|
|
547
|
+
try {
|
|
548
|
+
await stub.fetch("http://do/invalidate", {
|
|
549
|
+
method: "POST",
|
|
550
|
+
headers: { "Content-Type": "application/json" },
|
|
551
|
+
body: JSON.stringify({ templateId })
|
|
552
|
+
});
|
|
553
|
+
} catch (e) {
|
|
554
|
+
console.warn("[DOCacheProvider] Failed to invalidate template:", e);
|
|
555
|
+
}
|
|
556
|
+
},
|
|
557
|
+
async invalidateSettings(profile, tenantId) {
|
|
558
|
+
const key = `${profile}:${tenantId || ""}`;
|
|
559
|
+
try {
|
|
560
|
+
await stub.fetch("http://do/settings/invalidate", {
|
|
561
|
+
method: "POST",
|
|
562
|
+
headers: { "Content-Type": "application/json" },
|
|
563
|
+
body: JSON.stringify({ key })
|
|
564
|
+
});
|
|
565
|
+
} catch (e) {
|
|
566
|
+
console.warn("[DOCacheProvider] Failed to invalidate settings:", e);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// src/backend/EmailService.js
|
|
573
|
+
var EmailService = class {
|
|
574
|
+
/**
|
|
575
|
+
* @param {Object} env - Cloudflare environment bindings (DB, etc.)
|
|
576
|
+
* @param {Object} config - Configuration options
|
|
577
|
+
* @param {string} [config.emailTablePrefix='system_email_'] - Prefix for D1 tables
|
|
578
|
+
* @param {Object} [config.defaults] - Default settings (fromName, fromAddress)
|
|
579
|
+
* @param {Object} [cacheProvider] - Optional cache interface (DO stub or KV wrapper)
|
|
580
|
+
*/
|
|
581
|
+
constructor(env, config = {}, cacheProvider = null) {
|
|
582
|
+
var _a, _b, _c;
|
|
583
|
+
this.env = env;
|
|
584
|
+
this.db = env.DB;
|
|
585
|
+
this.config = {
|
|
586
|
+
emailTablePrefix: config.emailTablePrefix || config.tableNamePrefix || "system_email_",
|
|
587
|
+
defaults: config.defaults || {
|
|
588
|
+
fromName: "System",
|
|
589
|
+
fromAddress: "noreply@example.com",
|
|
590
|
+
provider: "mailchannels"
|
|
591
|
+
},
|
|
592
|
+
// Loader function to fetch settings from backend (DB, KV, etc.)
|
|
593
|
+
// Signature: async (profile, tenantId) => SettingsObject
|
|
594
|
+
settingsLoader: config.settingsLoader || null,
|
|
595
|
+
// Updater function to save settings to backend
|
|
596
|
+
// Signature: async (profile, tenantId, settings) => void
|
|
597
|
+
settingsUpdater: config.settingsUpdater || null,
|
|
598
|
+
// Branding configuration for email templates
|
|
599
|
+
branding: {
|
|
600
|
+
brandName: ((_a = config.branding) == null ? void 0 : _a.brandName) || "Your App",
|
|
601
|
+
portalUrl: ((_b = config.branding) == null ? void 0 : _b.portalUrl) || "https://app.example.com",
|
|
602
|
+
primaryColor: ((_c = config.branding) == null ? void 0 : _c.primaryColor) || "#667eea",
|
|
603
|
+
...config.branding
|
|
604
|
+
},
|
|
605
|
+
...config
|
|
606
|
+
};
|
|
607
|
+
if (!cacheProvider && env.EMAIL_TEMPLATE_CACHE) {
|
|
608
|
+
this.cache = createDOCacheProvider(env.EMAIL_TEMPLATE_CACHE);
|
|
609
|
+
} else {
|
|
610
|
+
this.cache = cacheProvider;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
// --- Configuration & Settings ---
|
|
614
|
+
/**
|
|
615
|
+
* Load email configuration
|
|
616
|
+
* @param {string} profile - 'system' or 'tenant' (or custom profile string)
|
|
617
|
+
* @param {string} tenantId - Context ID (optional)
|
|
618
|
+
* @returns {Promise<Object>} Email configuration
|
|
619
|
+
*/
|
|
620
|
+
async loadSettings(profile = "system", tenantId = null) {
|
|
621
|
+
if (this.cache && this.cache.getSettings) {
|
|
622
|
+
try {
|
|
623
|
+
const cached = await this.cache.getSettings(profile, tenantId);
|
|
624
|
+
if (cached) return this._normalizeConfig(cached);
|
|
625
|
+
} catch (e) {
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
let settings = null;
|
|
629
|
+
if (this.config.settingsLoader) {
|
|
630
|
+
try {
|
|
631
|
+
settings = await this.config.settingsLoader(profile, tenantId);
|
|
632
|
+
} catch (e) {
|
|
633
|
+
console.warn("[EmailService] settingsLoader failed:", e);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
if (settings) {
|
|
637
|
+
if (this.cache && this.cache.putSettings) {
|
|
638
|
+
try {
|
|
639
|
+
this.cache.putSettings(profile, tenantId, settings);
|
|
640
|
+
} catch (e) {
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return this._normalizeConfig(settings);
|
|
644
|
+
}
|
|
645
|
+
return {
|
|
646
|
+
...this.config.defaults
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Normalize config keys to standard format
|
|
651
|
+
* Handles both snake_case (DB) and camelCase inputs
|
|
652
|
+
*/
|
|
653
|
+
_normalizeConfig(config) {
|
|
654
|
+
return {
|
|
655
|
+
provider: config.email_provider || config.provider || this.config.defaults.provider,
|
|
656
|
+
fromAddress: config.email_from_address || config.fromAddress || this.config.defaults.fromAddress,
|
|
657
|
+
fromName: config.email_from_name || config.fromName || this.config.defaults.fromName,
|
|
658
|
+
// Provider-specific settings (normalize DB keys to service keys)
|
|
659
|
+
sendgridApiKey: config.sendgrid_api_key || config.sendgridApiKey,
|
|
660
|
+
resendApiKey: config.resend_api_key || config.resendApiKey,
|
|
661
|
+
sendpulseClientId: config.sendpulse_client_id || config.sendpulseClientId,
|
|
662
|
+
sendpulseClientSecret: config.sendpulse_client_secret || config.sendpulseClientSecret,
|
|
663
|
+
// SMTP
|
|
664
|
+
smtpHost: config.smtp_host || config.smtpHost,
|
|
665
|
+
smtpPort: config.smtp_port || config.smtpPort,
|
|
666
|
+
smtpUsername: config.smtp_username || config.smtpUsername,
|
|
667
|
+
smtpPassword: config.smtp_password || config.smtpPassword,
|
|
668
|
+
// Tracking
|
|
669
|
+
trackingUrl: config.tracking_url || config.trackingUrl,
|
|
670
|
+
// Pass through others
|
|
671
|
+
// Pass through others
|
|
672
|
+
...config,
|
|
673
|
+
smtpSecure: config.smtp_secure === "true"
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
// --- Template Management ---
|
|
677
|
+
async getTemplate(templateId) {
|
|
678
|
+
if (this.cache) {
|
|
679
|
+
try {
|
|
680
|
+
const cached = await this.cache.getTemplate(templateId);
|
|
681
|
+
if (cached) return cached;
|
|
682
|
+
} catch (e) {
|
|
683
|
+
console.warn("[EmailService] Template cache lookup failed:", e);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
const table = `${this.config.emailTablePrefix}templates`;
|
|
687
|
+
return await this.db.prepare(`SELECT * FROM ${table} WHERE template_id = ?`).bind(templateId).first();
|
|
688
|
+
}
|
|
689
|
+
async getAllTemplates() {
|
|
690
|
+
const table = `${this.config.emailTablePrefix}templates`;
|
|
691
|
+
const result = await this.db.prepare(`SELECT * FROM ${table} ORDER BY template_name`).all();
|
|
692
|
+
return result.results || [];
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Save email configuration
|
|
696
|
+
* @param {Object} settings - Config object
|
|
697
|
+
* @param {string} profile - 'system' or 'tenant'
|
|
698
|
+
* @param {string} tenantId - Context ID
|
|
699
|
+
*/
|
|
700
|
+
async saveSettings(settings, profile = "system", tenantId = null) {
|
|
701
|
+
if (this.config.settingsUpdater) {
|
|
702
|
+
try {
|
|
703
|
+
await this.config.settingsUpdater(profile, tenantId, settings);
|
|
704
|
+
} catch (e) {
|
|
705
|
+
console.error("[EmailService] settingsUpdater failed:", e);
|
|
706
|
+
throw e;
|
|
707
|
+
}
|
|
708
|
+
} else if (profile === "system" && this.db) {
|
|
709
|
+
}
|
|
710
|
+
if (this.cache && this.cache.invalidateSettings) {
|
|
711
|
+
try {
|
|
712
|
+
await this.cache.invalidateSettings(profile, tenantId);
|
|
713
|
+
} catch (e) {
|
|
714
|
+
console.warn("[EmailService] Failed to invalidate settings cache:", e);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
async saveTemplate(template, userId = "system") {
|
|
719
|
+
const table = `${this.config.emailTablePrefix}templates`;
|
|
720
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
721
|
+
const existing = await this.getTemplate(template.template_id);
|
|
722
|
+
if (existing) {
|
|
723
|
+
await this.db.prepare(`
|
|
724
|
+
UPDATE ${table} SET
|
|
725
|
+
template_name = ?, template_type = ?, subject_template = ?,
|
|
726
|
+
body_markdown = ?, variables = ?, description = ?, is_active = ?,
|
|
727
|
+
updated_at = ?, updated_by = ?
|
|
728
|
+
WHERE template_id = ?
|
|
729
|
+
`).bind(
|
|
730
|
+
template.template_name,
|
|
731
|
+
template.template_type,
|
|
732
|
+
template.subject_template,
|
|
733
|
+
template.body_markdown,
|
|
734
|
+
template.variables,
|
|
735
|
+
template.description,
|
|
736
|
+
template.is_active,
|
|
737
|
+
now,
|
|
738
|
+
userId,
|
|
739
|
+
template.template_id
|
|
740
|
+
).run();
|
|
741
|
+
} else {
|
|
742
|
+
await this.db.prepare(`
|
|
743
|
+
INSERT INTO ${table} (
|
|
744
|
+
template_id, template_name, template_type, subject_template,
|
|
745
|
+
body_markdown, variables, description, is_active, created_at, updated_at, updated_by
|
|
746
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
747
|
+
`).bind(
|
|
748
|
+
template.template_id,
|
|
749
|
+
template.template_name,
|
|
750
|
+
template.template_type,
|
|
751
|
+
template.subject_template,
|
|
752
|
+
template.body_markdown,
|
|
753
|
+
template.variables || "[]",
|
|
754
|
+
template.description,
|
|
755
|
+
template.is_active || 1,
|
|
756
|
+
now,
|
|
757
|
+
now,
|
|
758
|
+
userId
|
|
759
|
+
).run();
|
|
760
|
+
}
|
|
761
|
+
if (this.cache) {
|
|
762
|
+
await this.cache.putTemplate(template);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
async deleteTemplate(templateId) {
|
|
766
|
+
const table = `${this.config.emailTablePrefix}templates`;
|
|
767
|
+
await this.db.prepare(`DELETE FROM ${table} WHERE template_id = ?`).bind(templateId).run();
|
|
768
|
+
if (this.cache) {
|
|
769
|
+
await this.cache.deleteTemplate(templateId);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
// --- Rendering ---
|
|
773
|
+
async renderTemplate(templateId, data) {
|
|
774
|
+
const template = await this.getTemplate(templateId);
|
|
775
|
+
if (!template) throw new Error(`Template not found: ${templateId}`);
|
|
776
|
+
const subject = import_mustache.default.render(template.subject_template, data);
|
|
777
|
+
const markdown = import_mustache.default.render(template.body_markdown, data);
|
|
778
|
+
import_marked.marked.use({ mangle: false, headerIds: false });
|
|
779
|
+
const htmlContent = import_marked.marked.parse(markdown);
|
|
780
|
+
const html = this.wrapInBaseTemplate(htmlContent, subject, data);
|
|
781
|
+
const plainText = markdown.replace(/<[^>]*>/g, "");
|
|
782
|
+
return { subject, html, plainText };
|
|
783
|
+
}
|
|
784
|
+
wrapInBaseTemplate(content, subject, data = {}) {
|
|
785
|
+
const templateData = {
|
|
786
|
+
...data,
|
|
787
|
+
brandName: data.brandName || this.config.branding.brandName,
|
|
788
|
+
portalUrl: data.portalUrl || this.config.branding.portalUrl,
|
|
789
|
+
unsubscribeUrl: data.unsubscribeUrl || "{{unsubscribe_url}}"
|
|
790
|
+
};
|
|
791
|
+
return wrapInEmailTemplate(content, subject, templateData);
|
|
792
|
+
}
|
|
793
|
+
// --- Delivery ---
|
|
794
|
+
/**
|
|
795
|
+
* Send a single email
|
|
796
|
+
* @param {Object} params - Email parameters
|
|
797
|
+
* @param {string} params.to - Recipient email
|
|
798
|
+
* @param {string} params.subject - Email subject
|
|
799
|
+
* @param {string} params.html - HTML body
|
|
800
|
+
* @param {string} params.text - Plain text body
|
|
801
|
+
* @param {string} [params.provider] - Override provider
|
|
802
|
+
* @param {string} [params.profile='system'] - 'system' or 'tenant'
|
|
803
|
+
* @param {string} [params.tenantId] - Required if profile is 'tenant'
|
|
804
|
+
* @param {Object} [params.metadata] - Additional metadata
|
|
805
|
+
* @returns {Promise<Object>} Delivery result
|
|
806
|
+
*/
|
|
807
|
+
async sendEmail({ to, subject, html, htmlBody, text, textBody, provider, profile = "system", tenantId = null, metadata = {} }) {
|
|
808
|
+
const htmlContent = html || htmlBody;
|
|
809
|
+
const textContent = text || textBody;
|
|
810
|
+
try {
|
|
811
|
+
const settings = await this.loadSettings(profile, tenantId);
|
|
812
|
+
const useProvider = provider || settings.provider || "mailchannels";
|
|
813
|
+
let result;
|
|
814
|
+
switch (useProvider) {
|
|
815
|
+
case "mailchannels":
|
|
816
|
+
result = await this.sendViaMailChannels(to, subject, htmlContent, textContent, settings, metadata);
|
|
817
|
+
break;
|
|
818
|
+
case "sendgrid":
|
|
819
|
+
result = await this.sendViaSendGrid(to, subject, htmlContent, textContent, settings, metadata);
|
|
820
|
+
break;
|
|
821
|
+
case "resend":
|
|
822
|
+
result = await this.sendViaResend(to, subject, htmlContent, textContent, settings, metadata);
|
|
823
|
+
break;
|
|
824
|
+
case "sendpulse":
|
|
825
|
+
result = await this.sendViaSendPulse(to, subject, htmlContent, textContent, settings, metadata);
|
|
826
|
+
break;
|
|
827
|
+
default:
|
|
828
|
+
console.error(`[EmailService] Unknown provider: ${useProvider}`);
|
|
829
|
+
return { success: false, error: `Unknown email provider: ${useProvider}` };
|
|
830
|
+
}
|
|
831
|
+
if (result) {
|
|
832
|
+
return { success: true, messageId: crypto.randomUUID() };
|
|
833
|
+
} else {
|
|
834
|
+
console.error("[EmailService] Failed to send email to:", to);
|
|
835
|
+
return { success: false, error: "Failed to send email" };
|
|
836
|
+
}
|
|
837
|
+
} catch (error) {
|
|
838
|
+
console.error("[EmailService] Error sending email:", error);
|
|
839
|
+
return { success: false, error: error.message };
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Send multiple emails in batch
|
|
844
|
+
* @param {Array} emails - Array of email objects
|
|
845
|
+
* @returns {Promise<Array>} Array of delivery results
|
|
846
|
+
*/
|
|
847
|
+
async sendBatch(emails) {
|
|
848
|
+
console.log("[EmailService] Sending batch of", emails.length, "emails");
|
|
849
|
+
const results = await Promise.all(
|
|
850
|
+
emails.map((email) => this.sendEmail(email))
|
|
851
|
+
);
|
|
852
|
+
return results;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Send email via MailChannels HTTP API
|
|
856
|
+
* MailChannels is specifically designed for Cloudflare Workers
|
|
857
|
+
*/
|
|
858
|
+
async sendViaMailChannels(to, subject, html, text, settings, metadata) {
|
|
859
|
+
try {
|
|
860
|
+
const response = await fetch("https://api.mailchannels.net/tx/v1/send", {
|
|
861
|
+
method: "POST",
|
|
862
|
+
headers: { "Content-Type": "application/json" },
|
|
863
|
+
body: JSON.stringify({
|
|
864
|
+
personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
|
|
865
|
+
from: { email: settings.fromAddress, name: settings.fromName },
|
|
866
|
+
subject,
|
|
867
|
+
content: [
|
|
868
|
+
{ type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") },
|
|
869
|
+
{ type: "text/html", value: html }
|
|
870
|
+
]
|
|
871
|
+
})
|
|
872
|
+
});
|
|
873
|
+
if (response.status === 202) {
|
|
874
|
+
return true;
|
|
875
|
+
} else {
|
|
876
|
+
const contentType = response.headers.get("content-type");
|
|
877
|
+
const errorBody = (contentType == null ? void 0 : contentType.includes("application/json")) ? await response.json() : await response.text();
|
|
878
|
+
console.error("[EmailService] MailChannels error:", response.status, errorBody);
|
|
879
|
+
return false;
|
|
880
|
+
}
|
|
881
|
+
} catch (error) {
|
|
882
|
+
console.error("[EmailService] MailChannels exception:", error.message);
|
|
883
|
+
return false;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* Send email via SendGrid HTTP API
|
|
888
|
+
*/
|
|
889
|
+
async sendViaSendGrid(to, subject, html, text, settings, metadata) {
|
|
890
|
+
try {
|
|
891
|
+
if (!settings.sendgridApiKey) {
|
|
892
|
+
console.error("[EmailService] SendGrid API key missing");
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
const response = await fetch("https://api.sendgrid.com/v3/mail/send", {
|
|
896
|
+
method: "POST",
|
|
897
|
+
headers: {
|
|
898
|
+
"Authorization": `Bearer ${settings.sendgridApiKey}`,
|
|
899
|
+
"Content-Type": "application/json"
|
|
900
|
+
},
|
|
901
|
+
body: JSON.stringify({
|
|
902
|
+
personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
|
|
903
|
+
from: { email: settings.fromAddress, name: settings.fromName },
|
|
904
|
+
subject,
|
|
905
|
+
content: [
|
|
906
|
+
{ type: "text/html", value: html },
|
|
907
|
+
{ type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") }
|
|
908
|
+
]
|
|
909
|
+
})
|
|
910
|
+
});
|
|
911
|
+
if (response.status === 202) {
|
|
912
|
+
return true;
|
|
913
|
+
} else {
|
|
914
|
+
const errorText = await response.text();
|
|
915
|
+
console.error("[EmailService] SendGrid error:", response.status, errorText);
|
|
916
|
+
return false;
|
|
917
|
+
}
|
|
918
|
+
} catch (error) {
|
|
919
|
+
console.error("[EmailService] SendGrid exception:", error.message);
|
|
920
|
+
return false;
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Send email via Resend HTTP API
|
|
925
|
+
*/
|
|
926
|
+
async sendViaResend(to, subject, html, text, settings, metadata) {
|
|
927
|
+
try {
|
|
928
|
+
if (!settings.resendApiKey) {
|
|
929
|
+
console.error("[EmailService] Resend API key missing");
|
|
930
|
+
return false;
|
|
931
|
+
}
|
|
932
|
+
const response = await fetch("https://api.resend.com/emails", {
|
|
933
|
+
method: "POST",
|
|
934
|
+
headers: {
|
|
935
|
+
"Authorization": `Bearer ${settings.resendApiKey}`,
|
|
936
|
+
"Content-Type": "application/json"
|
|
937
|
+
},
|
|
938
|
+
body: JSON.stringify({
|
|
939
|
+
from: `${settings.fromName} <${settings.fromAddress}>`,
|
|
940
|
+
to: [to],
|
|
941
|
+
subject,
|
|
942
|
+
html,
|
|
943
|
+
text: text || html.replace(/<[^>]*>/g, "")
|
|
944
|
+
})
|
|
945
|
+
});
|
|
946
|
+
if (response.ok) {
|
|
947
|
+
return true;
|
|
948
|
+
} else {
|
|
949
|
+
const errorText = await response.text();
|
|
950
|
+
console.error("[EmailService] Resend error:", response.status, errorText);
|
|
951
|
+
return false;
|
|
952
|
+
}
|
|
953
|
+
} catch (error) {
|
|
954
|
+
console.error("[EmailService] Resend exception:", error.message);
|
|
955
|
+
return false;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Send email via SendPulse HTTP API
|
|
960
|
+
* SendPulse offers 15,000 free emails/month
|
|
961
|
+
*/
|
|
962
|
+
async sendViaSendPulse(to, subject, html, text, settings, metadata) {
|
|
963
|
+
try {
|
|
964
|
+
if (!settings.sendpulseClientId || !settings.sendpulseClientSecret) {
|
|
965
|
+
console.error("[EmailService] SendPulse credentials missing");
|
|
966
|
+
return false;
|
|
967
|
+
}
|
|
968
|
+
const tokenParams = new URLSearchParams({
|
|
969
|
+
grant_type: "client_credentials",
|
|
970
|
+
client_id: settings.sendpulseClientId,
|
|
971
|
+
client_secret: settings.sendpulseClientSecret
|
|
972
|
+
});
|
|
973
|
+
const tokenResponse = await fetch("https://api.sendpulse.com/oauth/access_token", {
|
|
974
|
+
method: "POST",
|
|
975
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
976
|
+
body: tokenParams.toString()
|
|
977
|
+
});
|
|
978
|
+
if (!tokenResponse.ok) {
|
|
979
|
+
const error = await tokenResponse.text();
|
|
980
|
+
console.error("[EmailService] SendPulse auth error:", error);
|
|
981
|
+
return false;
|
|
982
|
+
}
|
|
983
|
+
const tokenData = await tokenResponse.json();
|
|
984
|
+
if (!tokenData.access_token) {
|
|
985
|
+
console.error("[EmailService] SendPulse: No access token in response");
|
|
986
|
+
return false;
|
|
987
|
+
}
|
|
988
|
+
const { access_token } = tokenData;
|
|
989
|
+
const toBase64 = (str) => {
|
|
990
|
+
if (!str) return "";
|
|
991
|
+
return Buffer.from(String(str)).toString("base64");
|
|
992
|
+
};
|
|
993
|
+
const htmlSafe = html || "";
|
|
994
|
+
const textSafe = text || (htmlSafe ? htmlSafe.replace(/<[^>]*>/g, "") : "");
|
|
995
|
+
const response = await fetch("https://api.sendpulse.com/smtp/emails", {
|
|
996
|
+
method: "POST",
|
|
997
|
+
headers: {
|
|
998
|
+
"Authorization": `Bearer ${access_token}`,
|
|
999
|
+
"Content-Type": "application/json"
|
|
1000
|
+
},
|
|
1001
|
+
body: JSON.stringify({
|
|
1002
|
+
email: {
|
|
1003
|
+
html: toBase64(htmlSafe),
|
|
1004
|
+
text: toBase64(textSafe),
|
|
1005
|
+
subject,
|
|
1006
|
+
from: { name: settings.fromName, email: settings.fromAddress },
|
|
1007
|
+
to: [{ name: metadata.recipientName || "", email: to }]
|
|
1008
|
+
}
|
|
1009
|
+
})
|
|
1010
|
+
});
|
|
1011
|
+
if (response.ok) {
|
|
1012
|
+
return true;
|
|
1013
|
+
} else {
|
|
1014
|
+
const errorText = await response.text();
|
|
1015
|
+
console.error("[EmailService] SendPulse send error:", response.status, errorText);
|
|
1016
|
+
return false;
|
|
1017
|
+
}
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
console.error("[EmailService] SendPulse exception:", error.message);
|
|
1020
|
+
return false;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
};
|
|
1024
|
+
|
|
1025
|
+
// src/backend/routes/index.js
|
|
1026
|
+
var import_hono3 = require("hono");
|
|
1027
|
+
|
|
1028
|
+
// src/backend/routes/templates.js
|
|
1029
|
+
var import_hono = require("hono");
|
|
1030
|
+
function createTemplateRoutes(env, config = {}, cacheProvider = null) {
|
|
1031
|
+
const app = new import_hono.Hono();
|
|
1032
|
+
const emailService = new EmailService(env, config, cacheProvider);
|
|
1033
|
+
app.get("/templates", async (c) => {
|
|
1034
|
+
try {
|
|
1035
|
+
const templates = await emailService.getAllTemplates();
|
|
1036
|
+
return c.json({ success: true, templates });
|
|
1037
|
+
} catch (err) {
|
|
1038
|
+
return c.json({ success: false, error: err.message }, 500);
|
|
1039
|
+
}
|
|
1040
|
+
});
|
|
1041
|
+
app.get("/templates/:id", async (c) => {
|
|
1042
|
+
try {
|
|
1043
|
+
const template = await emailService.getTemplate(c.req.param("id"));
|
|
1044
|
+
if (!template) return c.json({ success: false, error: "Template not found" }, 404);
|
|
1045
|
+
return c.json({ success: true, template });
|
|
1046
|
+
} catch (err) {
|
|
1047
|
+
return c.json({ success: false, error: err.message }, 500);
|
|
1048
|
+
}
|
|
1049
|
+
});
|
|
1050
|
+
app.post("/templates", async (c) => {
|
|
1051
|
+
try {
|
|
1052
|
+
const data = await c.req.json();
|
|
1053
|
+
await emailService.saveTemplate(data, "admin");
|
|
1054
|
+
return c.json({ success: true, message: "Template saved" });
|
|
1055
|
+
} catch (err) {
|
|
1056
|
+
return c.json({ success: false, error: err.message }, 500);
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
app.delete("/templates/:id", async (c) => {
|
|
1060
|
+
try {
|
|
1061
|
+
await emailService.deleteTemplate(c.req.param("id"));
|
|
1062
|
+
return c.json({ success: true, message: "Template deleted" });
|
|
1063
|
+
} catch (err) {
|
|
1064
|
+
return c.json({ success: false, error: err.message }, 500);
|
|
1065
|
+
}
|
|
1066
|
+
});
|
|
1067
|
+
app.post("/templates/:id/preview", async (c) => {
|
|
1068
|
+
try {
|
|
1069
|
+
const id = c.req.param("id");
|
|
1070
|
+
const data = await c.req.json();
|
|
1071
|
+
const result = await emailService.renderTemplate(id, data);
|
|
1072
|
+
return c.json({ success: true, preview: result });
|
|
1073
|
+
} catch (err) {
|
|
1074
|
+
return c.json({ success: false, error: err.message }, 500);
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
app.post("/templates/:id/test", async (c) => {
|
|
1078
|
+
try {
|
|
1079
|
+
const id = c.req.param("id");
|
|
1080
|
+
const { to, data } = await c.req.json();
|
|
1081
|
+
const { subject, html, plainText } = await emailService.renderTemplate(id, data);
|
|
1082
|
+
const result = await emailService.sendEmail({
|
|
1083
|
+
to,
|
|
1084
|
+
subject: `[TEST] ${subject}`,
|
|
1085
|
+
html,
|
|
1086
|
+
text: plainText
|
|
1087
|
+
});
|
|
1088
|
+
if (result.success) {
|
|
1089
|
+
return c.json({ success: true, message: "Test email sent" });
|
|
1090
|
+
} else {
|
|
1091
|
+
return c.json({ success: false, error: result.error }, 500);
|
|
1092
|
+
}
|
|
1093
|
+
} catch (err) {
|
|
1094
|
+
return c.json({ success: false, error: err.message }, 500);
|
|
1095
|
+
}
|
|
1096
|
+
});
|
|
1097
|
+
return app;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// src/backend/routes/tracking.js
|
|
1101
|
+
var import_hono2 = require("hono");
|
|
1102
|
+
var TRACKING_PIXEL = new Uint8Array([
|
|
1103
|
+
71,
|
|
1104
|
+
73,
|
|
1105
|
+
70,
|
|
1106
|
+
56,
|
|
1107
|
+
57,
|
|
1108
|
+
97,
|
|
1109
|
+
1,
|
|
1110
|
+
0,
|
|
1111
|
+
1,
|
|
1112
|
+
0,
|
|
1113
|
+
128,
|
|
1114
|
+
0,
|
|
1115
|
+
0,
|
|
1116
|
+
0,
|
|
1117
|
+
0,
|
|
1118
|
+
0,
|
|
1119
|
+
255,
|
|
1120
|
+
255,
|
|
1121
|
+
255,
|
|
1122
|
+
33,
|
|
1123
|
+
249,
|
|
1124
|
+
4,
|
|
1125
|
+
1,
|
|
1126
|
+
0,
|
|
1127
|
+
0,
|
|
1128
|
+
0,
|
|
1129
|
+
0,
|
|
1130
|
+
44,
|
|
1131
|
+
0,
|
|
1132
|
+
0,
|
|
1133
|
+
0,
|
|
1134
|
+
0,
|
|
1135
|
+
1,
|
|
1136
|
+
0,
|
|
1137
|
+
1,
|
|
1138
|
+
0,
|
|
1139
|
+
0,
|
|
1140
|
+
2,
|
|
1141
|
+
1,
|
|
1142
|
+
68,
|
|
1143
|
+
0,
|
|
1144
|
+
59
|
|
1145
|
+
]);
|
|
1146
|
+
function createTrackingRoutes(env, config = {}) {
|
|
1147
|
+
const app = new import_hono2.Hono();
|
|
1148
|
+
const db = env.DB;
|
|
1149
|
+
const tablePrefix = config.emailTablePrefix || config.tableNamePrefix || "system_email_";
|
|
1150
|
+
app.get("/track/open/:token", async (c) => {
|
|
1151
|
+
const token = c.req.param("token");
|
|
1152
|
+
try {
|
|
1153
|
+
const sendId = token;
|
|
1154
|
+
const send = await db.prepare(`SELECT * FROM ${tablePrefix}sends WHERE send_id = ?`).bind(sendId).first();
|
|
1155
|
+
if (send) {
|
|
1156
|
+
const eventId = crypto.randomUUID();
|
|
1157
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1158
|
+
await db.prepare(
|
|
1159
|
+
`INSERT INTO ${tablePrefix}events (
|
|
1160
|
+
event_id, send_id, user_id, tenant_id, email_kind, event_type, metadata, created_at
|
|
1161
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1162
|
+
).bind(
|
|
1163
|
+
eventId,
|
|
1164
|
+
sendId,
|
|
1165
|
+
send.user_id,
|
|
1166
|
+
send.tenant_id,
|
|
1167
|
+
send.email_kind,
|
|
1168
|
+
"opened",
|
|
1169
|
+
JSON.stringify({
|
|
1170
|
+
user_agent: c.req.header("user-agent"),
|
|
1171
|
+
referer: c.req.header("referer")
|
|
1172
|
+
}),
|
|
1173
|
+
now
|
|
1174
|
+
).run();
|
|
1175
|
+
}
|
|
1176
|
+
} catch (error) {
|
|
1177
|
+
console.error("[EmailTracking] Error tracking email open:", error);
|
|
1178
|
+
}
|
|
1179
|
+
return new Response(TRACKING_PIXEL, {
|
|
1180
|
+
headers: {
|
|
1181
|
+
"Content-Type": "image/gif",
|
|
1182
|
+
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
1183
|
+
"Pragma": "no-cache",
|
|
1184
|
+
"Expires": "0"
|
|
1185
|
+
}
|
|
1186
|
+
});
|
|
1187
|
+
});
|
|
1188
|
+
app.post("/track/click/:token", async (c) => {
|
|
1189
|
+
const token = c.req.param("token");
|
|
1190
|
+
let url;
|
|
1191
|
+
try {
|
|
1192
|
+
const body = await c.req.json();
|
|
1193
|
+
url = body.url;
|
|
1194
|
+
} catch {
|
|
1195
|
+
return c.json({ success: false, error: "Invalid request body" }, 400);
|
|
1196
|
+
}
|
|
1197
|
+
if (!url) {
|
|
1198
|
+
return c.json({ success: false, error: "Missing URL" }, 400);
|
|
1199
|
+
}
|
|
1200
|
+
try {
|
|
1201
|
+
const sendId = token;
|
|
1202
|
+
const send = await db.prepare(`SELECT * FROM ${tablePrefix}sends WHERE send_id = ?`).bind(sendId).first();
|
|
1203
|
+
if (send) {
|
|
1204
|
+
const eventId = crypto.randomUUID();
|
|
1205
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1206
|
+
await db.prepare(
|
|
1207
|
+
`INSERT INTO ${tablePrefix}events (
|
|
1208
|
+
event_id, send_id, user_id, tenant_id, email_kind, event_type, metadata, created_at
|
|
1209
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1210
|
+
).bind(
|
|
1211
|
+
eventId,
|
|
1212
|
+
sendId,
|
|
1213
|
+
send.user_id,
|
|
1214
|
+
send.tenant_id,
|
|
1215
|
+
send.email_kind,
|
|
1216
|
+
"clicked",
|
|
1217
|
+
JSON.stringify({
|
|
1218
|
+
url,
|
|
1219
|
+
user_agent: c.req.header("user-agent"),
|
|
1220
|
+
referer: c.req.header("referer")
|
|
1221
|
+
}),
|
|
1222
|
+
now
|
|
1223
|
+
).run();
|
|
1224
|
+
}
|
|
1225
|
+
return c.json({ success: true, tracked: !!send });
|
|
1226
|
+
} catch (error) {
|
|
1227
|
+
console.error("[EmailTracking] Error tracking email click:", error);
|
|
1228
|
+
return c.json({ success: false, error: "Failed to track click" }, 500);
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
app.get("/unsubscribe/:token", async (c) => {
|
|
1232
|
+
const unsubToken = c.req.param("token");
|
|
1233
|
+
try {
|
|
1234
|
+
const prefs = await db.prepare(`SELECT * FROM ${tablePrefix}preferences WHERE unsub_token = ?`).bind(unsubToken).first();
|
|
1235
|
+
if (!prefs) {
|
|
1236
|
+
return c.json({ success: false, error: "Invalid unsubscribe link" }, 404);
|
|
1237
|
+
}
|
|
1238
|
+
const currentSettings = JSON.parse(prefs.email_settings || "{}");
|
|
1239
|
+
const alreadyUnsubscribed = Object.keys(currentSettings).length === 0;
|
|
1240
|
+
if (!alreadyUnsubscribed) {
|
|
1241
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1242
|
+
await db.prepare(
|
|
1243
|
+
`UPDATE ${tablePrefix}preferences
|
|
1244
|
+
SET email_settings = '{}',
|
|
1245
|
+
updated_at = ?
|
|
1246
|
+
WHERE unsub_token = ?`
|
|
1247
|
+
).bind(now, unsubToken).run();
|
|
1248
|
+
const eventId = crypto.randomUUID();
|
|
1249
|
+
await db.prepare(
|
|
1250
|
+
`INSERT INTO ${tablePrefix}events (
|
|
1251
|
+
event_id, send_id, user_id, tenant_id, email_kind, event_type, metadata, created_at
|
|
1252
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1253
|
+
).bind(
|
|
1254
|
+
eventId,
|
|
1255
|
+
"unsubscribe",
|
|
1256
|
+
prefs.user_id,
|
|
1257
|
+
prefs.tenant_id,
|
|
1258
|
+
"all",
|
|
1259
|
+
"unsubscribed",
|
|
1260
|
+
JSON.stringify({
|
|
1261
|
+
user_agent: c.req.header("user-agent")
|
|
1262
|
+
}),
|
|
1263
|
+
now
|
|
1264
|
+
).run();
|
|
1265
|
+
}
|
|
1266
|
+
return c.json({ success: true, alreadyUnsubscribed });
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
console.error("[EmailTracking] Error processing unsubscribe:", error);
|
|
1269
|
+
return c.json({ success: false, error: "An error occurred" }, 500);
|
|
1270
|
+
}
|
|
1271
|
+
});
|
|
1272
|
+
return app;
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
// src/backend/routes/index.js
|
|
1276
|
+
function createEmailRoutes(env, config = {}, cacheProvider = null) {
|
|
1277
|
+
const app = new import_hono3.Hono();
|
|
1278
|
+
app.route("/api/email", createTemplateRoutes(env, config, cacheProvider));
|
|
1279
|
+
app.route("/email", createTrackingRoutes(env, config));
|
|
1280
|
+
return app;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
// src/common/utils.js
|
|
1284
|
+
var import_mustache2 = __toESM(require("mustache"), 1);
|
|
1285
|
+
var cachedWebsiteUrl = null;
|
|
1286
|
+
function getWebsiteUrl(env) {
|
|
1287
|
+
if (cachedWebsiteUrl) {
|
|
1288
|
+
return cachedWebsiteUrl;
|
|
1289
|
+
}
|
|
1290
|
+
const domain = env.DOMAIN || "x0start.com";
|
|
1291
|
+
const isDev = env.ENVIRONMENT === "development" || !env.ENVIRONMENT;
|
|
1292
|
+
const protocol = isDev ? "http" : "https";
|
|
1293
|
+
cachedWebsiteUrl = `${protocol}://www.${domain}`;
|
|
1294
|
+
return cachedWebsiteUrl;
|
|
1295
|
+
}
|
|
1296
|
+
function resetWebsiteUrlCache() {
|
|
1297
|
+
cachedWebsiteUrl = null;
|
|
1298
|
+
}
|
|
1299
|
+
function encodeTrackingLinks(html, sendId, env = null, websiteUrl = null) {
|
|
1300
|
+
const baseUrl = websiteUrl || (env ? getWebsiteUrl(env) : "https://www.x0start.com");
|
|
1301
|
+
const decodeHtmlEntities = (text) => {
|
|
1302
|
+
return text.replace(///g, "/").replace(/:/g, ":").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'");
|
|
1303
|
+
};
|
|
1304
|
+
return html.replace(/href="([^"]+)"/g, (match, url) => {
|
|
1305
|
+
if (url.startsWith("mailto:") || url.startsWith("tel:") || url.startsWith("#") || url.includes("{{") || // Skip template variables
|
|
1306
|
+
url.includes("/email/unsubscribe/") || url.includes("/email/track/")) {
|
|
1307
|
+
return match;
|
|
1308
|
+
}
|
|
1309
|
+
const decodedUrl = decodeHtmlEntities(url);
|
|
1310
|
+
const encodedUrl = Buffer.from(decodedUrl).toString("base64");
|
|
1311
|
+
const trackingUrl = `${baseUrl}/r/${sendId}?url=${encodedUrl}`;
|
|
1312
|
+
return `href="${trackingUrl}"`;
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
function markdownToPlainText(markdown) {
|
|
1316
|
+
return markdown.replace(/#{1,6}\s+/g, "").replace(/\*\*(.+?)\*\*/g, "$1").replace(/\*(.+?)\*/g, "$1").replace(/\[(.+?)\]\((.+?)\)/g, "$1: $2").replace(/`(.+?)`/g, "$1").replace(/>\s+/g, "").replace(/\n{3,}/g, "\n\n").trim();
|
|
1317
|
+
}
|
|
1318
|
+
function extractVariables(templateString) {
|
|
1319
|
+
if (!templateString) return [];
|
|
1320
|
+
try {
|
|
1321
|
+
const tokens = import_mustache2.default.parse(templateString);
|
|
1322
|
+
const variables = /* @__PURE__ */ new Set();
|
|
1323
|
+
const collectVariables = (tokenList) => {
|
|
1324
|
+
tokenList.forEach((token) => {
|
|
1325
|
+
const type = token[0];
|
|
1326
|
+
const value = token[1];
|
|
1327
|
+
if (type === "name" || type === "#" || type === "^" || type === "&") {
|
|
1328
|
+
variables.add(value);
|
|
1329
|
+
}
|
|
1330
|
+
if ((type === "#" || type === "^") && token[4]) {
|
|
1331
|
+
collectVariables(token[4]);
|
|
1332
|
+
}
|
|
1333
|
+
});
|
|
1334
|
+
};
|
|
1335
|
+
collectVariables(tokens);
|
|
1336
|
+
return Array.from(variables);
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
console.error("Error parsing template variables:", error);
|
|
1339
|
+
return [];
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// src/frontend/TemplateManager.jsx
|
|
1344
|
+
var import_react2 = __toESM(require("react"), 1);
|
|
1345
|
+
var import_lucide_react2 = require("lucide-react");
|
|
1346
|
+
|
|
1347
|
+
// src/frontend/TemplateEditor.jsx
|
|
1348
|
+
var import_react = __toESM(require("react"), 1);
|
|
1349
|
+
var import_lucide_react = require("lucide-react");
|
|
1350
|
+
var TemplateEditor = ({
|
|
1351
|
+
initialData,
|
|
1352
|
+
onSave,
|
|
1353
|
+
onCancel,
|
|
1354
|
+
onPreview,
|
|
1355
|
+
variablesHelpText = "Supports {{variable}}"
|
|
1356
|
+
}) => {
|
|
1357
|
+
const [formData, setFormData] = (0, import_react.useState)({
|
|
1358
|
+
template_id: "",
|
|
1359
|
+
template_name: "",
|
|
1360
|
+
template_type: "daily_reminder",
|
|
1361
|
+
subject_template: "",
|
|
1362
|
+
body_markdown: "",
|
|
1363
|
+
variables: "[]",
|
|
1364
|
+
description: "",
|
|
1365
|
+
is_active: 1,
|
|
1366
|
+
...initialData
|
|
1367
|
+
});
|
|
1368
|
+
const handleSubmit = (e) => {
|
|
1369
|
+
e.preventDefault();
|
|
1370
|
+
onSave(formData);
|
|
1371
|
+
};
|
|
1372
|
+
return /* @__PURE__ */ import_react.default.createElement("div", { className: "fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "p-6 border-b border-gray-200 flex justify-between items-center" }, /* @__PURE__ */ import_react.default.createElement("h2", { className: "text-xl font-bold text-gray-900" }, initialData ? "Edit Template" : "New Template"), /* @__PURE__ */ import_react.default.createElement("button", { onClick: onCancel, className: "p-2 hover:bg-gray-100 rounded-lg" }, /* @__PURE__ */ import_react.default.createElement(import_lucide_react.X, { className: "h-5 w-5" }))), /* @__PURE__ */ import_react.default.createElement("form", { onSubmit: handleSubmit, className: "flex-1 overflow-y-auto p-6 space-y-4" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "grid grid-cols-2 gap-4" }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("label", { className: "block text-sm font-medium text-gray-700 mb-1" }, "Template ID *"), /* @__PURE__ */ import_react.default.createElement(
|
|
1373
|
+
"input",
|
|
1374
|
+
{
|
|
1375
|
+
type: "text",
|
|
1376
|
+
required: true,
|
|
1377
|
+
disabled: !!initialData,
|
|
1378
|
+
value: formData.template_id,
|
|
1379
|
+
onChange: (e) => setFormData({ ...formData, template_id: e.target.value }),
|
|
1380
|
+
className: "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
|
|
1381
|
+
}
|
|
1382
|
+
)), /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("label", { className: "block text-sm font-medium text-gray-700 mb-1" }, "Name *"), /* @__PURE__ */ import_react.default.createElement(
|
|
1383
|
+
"input",
|
|
1384
|
+
{
|
|
1385
|
+
type: "text",
|
|
1386
|
+
required: true,
|
|
1387
|
+
value: formData.template_name,
|
|
1388
|
+
onChange: (e) => setFormData({ ...formData, template_name: e.target.value }),
|
|
1389
|
+
className: "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
|
|
1390
|
+
}
|
|
1391
|
+
))), /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("label", { className: "block text-sm font-medium text-gray-700 mb-1" }, "Subject *"), /* @__PURE__ */ import_react.default.createElement(
|
|
1392
|
+
"input",
|
|
1393
|
+
{
|
|
1394
|
+
type: "text",
|
|
1395
|
+
required: true,
|
|
1396
|
+
value: formData.subject_template,
|
|
1397
|
+
onChange: (e) => setFormData({ ...formData, subject_template: e.target.value }),
|
|
1398
|
+
className: "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
|
|
1399
|
+
}
|
|
1400
|
+
), /* @__PURE__ */ import_react.default.createElement("p", { className: "text-xs text-gray-500 mt-1" }, variablesHelpText)), /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("label", { className: "block text-sm font-medium text-gray-700 mb-1" }, "Body (Markdown) *"), /* @__PURE__ */ import_react.default.createElement(
|
|
1401
|
+
"textarea",
|
|
1402
|
+
{
|
|
1403
|
+
required: true,
|
|
1404
|
+
rows: 12,
|
|
1405
|
+
value: formData.body_markdown,
|
|
1406
|
+
onChange: (e) => setFormData({ ...formData, body_markdown: e.target.value }),
|
|
1407
|
+
className: "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono text-sm"
|
|
1408
|
+
}
|
|
1409
|
+
)), /* @__PURE__ */ import_react.default.createElement("div", { className: "flex justify-between pt-4" }, /* @__PURE__ */ import_react.default.createElement(
|
|
1410
|
+
"button",
|
|
1411
|
+
{
|
|
1412
|
+
type: "button",
|
|
1413
|
+
onClick: () => onPreview && onPreview(formData),
|
|
1414
|
+
className: "flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200"
|
|
1415
|
+
},
|
|
1416
|
+
/* @__PURE__ */ import_react.default.createElement(import_lucide_react.Eye, { className: "h-4 w-4" }),
|
|
1417
|
+
" Preview"
|
|
1418
|
+
), /* @__PURE__ */ import_react.default.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ import_react.default.createElement(
|
|
1419
|
+
"button",
|
|
1420
|
+
{
|
|
1421
|
+
type: "button",
|
|
1422
|
+
onClick: onCancel,
|
|
1423
|
+
className: "px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
|
|
1424
|
+
},
|
|
1425
|
+
"Cancel"
|
|
1426
|
+
), /* @__PURE__ */ import_react.default.createElement(
|
|
1427
|
+
"button",
|
|
1428
|
+
{
|
|
1429
|
+
type: "submit",
|
|
1430
|
+
className: "flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
|
|
1431
|
+
},
|
|
1432
|
+
/* @__PURE__ */ import_react.default.createElement(import_lucide_react.Save, { className: "h-4 w-4" }),
|
|
1433
|
+
" Save"
|
|
1434
|
+
))))));
|
|
1435
|
+
};
|
|
1436
|
+
|
|
1437
|
+
// src/frontend/TemplateManager.jsx
|
|
1438
|
+
var TemplateManager = ({
|
|
1439
|
+
apiClient,
|
|
1440
|
+
title = "Email Templates",
|
|
1441
|
+
description = "Manage your email templates"
|
|
1442
|
+
}) => {
|
|
1443
|
+
const [templates, setTemplates] = (0, import_react2.useState)([]);
|
|
1444
|
+
const [loading, setLoading] = (0, import_react2.useState)(true);
|
|
1445
|
+
const [showEditor, setShowEditor] = (0, import_react2.useState)(false);
|
|
1446
|
+
const [editingTemplate, setEditingTemplate] = (0, import_react2.useState)(null);
|
|
1447
|
+
(0, import_react2.useEffect)(() => {
|
|
1448
|
+
loadTemplates();
|
|
1449
|
+
}, []);
|
|
1450
|
+
const loadTemplates = async () => {
|
|
1451
|
+
try {
|
|
1452
|
+
setLoading(true);
|
|
1453
|
+
const res = await apiClient.get("/templates");
|
|
1454
|
+
if (res.data.success) {
|
|
1455
|
+
setTemplates(res.data.templates);
|
|
1456
|
+
}
|
|
1457
|
+
} catch (err) {
|
|
1458
|
+
console.error("Failed to load templates:", err);
|
|
1459
|
+
} finally {
|
|
1460
|
+
setLoading(false);
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
const handleSave = async (formData) => {
|
|
1464
|
+
try {
|
|
1465
|
+
await apiClient.post("/templates", formData);
|
|
1466
|
+
setShowEditor(false);
|
|
1467
|
+
loadTemplates();
|
|
1468
|
+
} catch (err) {
|
|
1469
|
+
console.error("Failed to save template:", err);
|
|
1470
|
+
alert("Failed to save template");
|
|
1471
|
+
}
|
|
1472
|
+
};
|
|
1473
|
+
const handleDelete = async (id) => {
|
|
1474
|
+
if (!confirm("Delete this template?")) return;
|
|
1475
|
+
try {
|
|
1476
|
+
await apiClient.delete(`/templates/${id}`);
|
|
1477
|
+
loadTemplates();
|
|
1478
|
+
} catch (err) {
|
|
1479
|
+
console.error("Failed to delete:", err);
|
|
1480
|
+
alert("Failed to delete template");
|
|
1481
|
+
}
|
|
1482
|
+
};
|
|
1483
|
+
return /* @__PURE__ */ import_react2.default.createElement("div", { className: "email-template-manager" }, /* @__PURE__ */ import_react2.default.createElement("div", { className: "flex justify-between items-center mb-6" }, /* @__PURE__ */ import_react2.default.createElement("div", null, /* @__PURE__ */ import_react2.default.createElement("h1", { className: "text-2xl font-bold text-gray-900" }, title), /* @__PURE__ */ import_react2.default.createElement("p", { className: "text-gray-600 mt-1" }, description)), /* @__PURE__ */ import_react2.default.createElement(
|
|
1484
|
+
"button",
|
|
1485
|
+
{
|
|
1486
|
+
onClick: () => {
|
|
1487
|
+
setEditingTemplate(null);
|
|
1488
|
+
setShowEditor(true);
|
|
1489
|
+
},
|
|
1490
|
+
className: "flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
|
|
1491
|
+
},
|
|
1492
|
+
/* @__PURE__ */ import_react2.default.createElement(import_lucide_react2.Plus, { className: "h-4 w-4" }),
|
|
1493
|
+
" New Template"
|
|
1494
|
+
)), loading ? /* @__PURE__ */ import_react2.default.createElement("div", { className: "flex justify-center p-12" }, /* @__PURE__ */ import_react2.default.createElement(import_lucide_react2.Loader, { className: "animate-spin text-gray-500" })) : /* @__PURE__ */ import_react2.default.createElement("div", { className: "grid gap-4" }, templates.map((t) => /* @__PURE__ */ import_react2.default.createElement("div", { key: t.template_id, className: "bg-white border rounded-lg p-6 flex justify-between items-start hover:shadow-md transition" }, /* @__PURE__ */ import_react2.default.createElement("div", null, /* @__PURE__ */ import_react2.default.createElement("div", { className: "flex items-center gap-3 mb-2" }, /* @__PURE__ */ import_react2.default.createElement(import_lucide_react2.Mail, { className: "h-5 w-5 text-blue-600" }), /* @__PURE__ */ import_react2.default.createElement("h3", { className: "text-lg font-semibold" }, t.template_name), /* @__PURE__ */ import_react2.default.createElement("span", { className: "px-2 py-1 text-xs bg-gray-100 rounded" }, t.template_type)), /* @__PURE__ */ import_react2.default.createElement("p", { className: "text-sm text-gray-600" }, t.description)), /* @__PURE__ */ import_react2.default.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ import_react2.default.createElement(
|
|
1495
|
+
"button",
|
|
1496
|
+
{
|
|
1497
|
+
onClick: () => {
|
|
1498
|
+
setEditingTemplate(t);
|
|
1499
|
+
setShowEditor(true);
|
|
1500
|
+
},
|
|
1501
|
+
className: "p-2 text-blue-600 hover:bg-blue-50 rounded"
|
|
1502
|
+
},
|
|
1503
|
+
/* @__PURE__ */ import_react2.default.createElement(import_lucide_react2.Edit2, { className: "h-4 w-4" })
|
|
1504
|
+
), /* @__PURE__ */ import_react2.default.createElement(
|
|
1505
|
+
"button",
|
|
1506
|
+
{
|
|
1507
|
+
onClick: () => handleDelete(t.template_id),
|
|
1508
|
+
className: "p-2 text-red-600 hover:bg-red-50 rounded"
|
|
1509
|
+
},
|
|
1510
|
+
/* @__PURE__ */ import_react2.default.createElement(import_lucide_react2.Trash2, { className: "h-4 w-4" })
|
|
1511
|
+
)))), templates.length === 0 && /* @__PURE__ */ import_react2.default.createElement("div", { className: "text-center py-12 text-gray-500 bg-gray-50 rounded border-dashed border-2" }, "No templates found. Create one to get started.")), showEditor && /* @__PURE__ */ import_react2.default.createElement(
|
|
1512
|
+
TemplateEditor,
|
|
1513
|
+
{
|
|
1514
|
+
initialData: editingTemplate,
|
|
1515
|
+
onSave: handleSave,
|
|
1516
|
+
onCancel: () => setShowEditor(false)
|
|
1517
|
+
}
|
|
1518
|
+
));
|
|
1519
|
+
};
|
|
1520
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1521
|
+
0 && (module.exports = {
|
|
1522
|
+
EmailService,
|
|
1523
|
+
EmailingCacheDO,
|
|
1524
|
+
TemplateEditor,
|
|
1525
|
+
TemplateManager,
|
|
1526
|
+
createDOCacheProvider,
|
|
1527
|
+
createEmailRoutes,
|
|
1528
|
+
createTemplateRoutes,
|
|
1529
|
+
createTrackingRoutes,
|
|
1530
|
+
encodeTrackingLinks,
|
|
1531
|
+
extractVariables,
|
|
1532
|
+
getWebsiteUrl,
|
|
1533
|
+
markdownToPlainText,
|
|
1534
|
+
resetWebsiteUrlCache,
|
|
1535
|
+
wrapInEmailTemplate
|
|
1536
|
+
});
|
|
1537
|
+
//# sourceMappingURL=index.cjs.map
|