@hintergrund/worker 0.3.10 → 0.3.12
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/README.md +4 -36
- package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/admin-users.handler.js +8 -5
- package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/setup.handler.js +56 -19
- package/dist/api/cms/handlers/website-repo.handler.d.ts +5 -0
- package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-repo.handler.js +30 -8
- package/dist/api/cms/routes/index.d.ts.map +1 -1
- package/dist/api/cms/routes/index.js +9 -2
- package/dist/api/emails/handlers/campaigns.handler.d.ts +1 -1
- package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/campaigns.handler.js +12 -13
- package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/public.handler.js +7 -10
- package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/send.handler.js +8 -14
- package/dist/api/emails/handlers/settings.handler.d.ts +4 -23
- package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/settings.handler.js +9 -19
- package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/admin.routes.js +2 -5
- package/dist/api/emails/routes/mail.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/mail.routes.js +62 -16
- package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/public.handler.js +18 -18
- package/dist/api/shop/routes.js +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -14
- package/dist/lib/design.d.ts +0 -1
- package/dist/lib/design.d.ts.map +1 -1
- package/dist/lib/design.js +1 -8
- package/dist/lib/email-template.d.ts +2 -12
- package/dist/lib/email-template.d.ts.map +1 -1
- package/dist/lib/email-template.js +3 -35
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +12 -1
- package/dist/lib/invoice.d.ts +2 -11
- package/dist/lib/invoice.d.ts.map +1 -1
- package/dist/lib/invoice.js +6 -39
- package/dist/lib/mail-schema.d.ts +1 -1
- package/dist/lib/mail-schema.d.ts.map +1 -1
- package/dist/lib/mail-schema.js +4 -1
- package/dist/lib/mail.d.ts.map +1 -1
- package/dist/lib/mail.js +11 -0
- package/dist/lib/project-db.d.ts +6 -1
- package/dist/lib/project-db.d.ts.map +1 -1
- package/dist/lib/project-db.js +9 -0
- package/dist/lib/website-i18n.d.ts +14 -6
- package/dist/lib/website-i18n.d.ts.map +1 -1
- package/dist/lib/website-i18n.js +37 -102
- package/dist/middleware/auth.d.ts +7 -0
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +14 -1
- package/package.json +2 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/settings.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"settings.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/settings.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAI/C,OAAO,EAA6G,KAAK,eAAe,EAAE,KAAK,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAE1N,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ;;GAGpD;AACD,iHAAiH;AACjH,wBAAsB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAIhF;AACD,sFAAsF;AACtF,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,cAAc,CAAC,CAG/E;AACD,6DAA6D;AAC7D,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,eAAe,CAAC,CAGjF"}
|
|
@@ -1,27 +1,17 @@
|
|
|
1
1
|
import { getGitHubConfig } from '../../../lib/config';
|
|
2
2
|
import { createGitHubClient } from '../../../lib/github';
|
|
3
3
|
import { readJsonConfig } from '../../../lib/github-config';
|
|
4
|
-
import { EMAIL_SETTINGS_PATH, EMAIL_TEMPLATES_PATH, LEGAL_CONTENT_PATH,
|
|
5
|
-
import { readDesign } from '../../../lib/design';
|
|
6
|
-
/** Reads the letterhead chosen in email settings and inlines it, as mail clients need a data URL. */
|
|
7
|
-
export async function resolveLogoDataUrl(github, logoPath) {
|
|
8
|
-
if (!logoPath)
|
|
9
|
-
return undefined;
|
|
10
|
-
const file = await github.readFileBinary(logoPath);
|
|
11
|
-
if (!file)
|
|
12
|
-
return undefined;
|
|
13
|
-
return `data:${/\.png$/i.test(logoPath) ? 'image/png' : 'image/jpeg'};base64,${file.content}`;
|
|
14
|
-
}
|
|
4
|
+
import { EMAIL_LAYOUT_PATH, EMAIL_SETTINGS_PATH, EMAIL_TEMPLATES_PATH, LEGAL_CONTENT_PATH, normalizeEmailTemplates } from '@hintergrund/runtime-contracts';
|
|
15
5
|
export async function readEmailSettings(env) {
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
const design = await readDesign(env);
|
|
19
|
-
return { settings: { ...data, emailTemplate: emailTemplateFromDesign(design, data.footerHtml) } };
|
|
6
|
+
const { data } = await readJsonConfig(createGitHubClient(getGitHubConfig(env)), EMAIL_SETTINGS_PATH, {});
|
|
7
|
+
return { settings: data };
|
|
20
8
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
|
|
9
|
+
/** The document every email is sent in. Its images and links are site paths; mail clients need absolute URLs. */
|
|
10
|
+
export async function readEmailLayout(env) {
|
|
11
|
+
const file = await createGitHubClient(getGitHubConfig(env)).readFile(EMAIL_LAYOUT_PATH);
|
|
12
|
+
if (!file || !env.PUBLIC_ORIGIN)
|
|
13
|
+
return file?.content;
|
|
14
|
+
return file.content.replace(/(src|href)="\/(?!\/)/g, `$1="${env.PUBLIC_ORIGIN.replace(/\/$/, '')}/`);
|
|
25
15
|
}
|
|
26
16
|
/** The copy of every automated email; a missing message falls back to the default. */
|
|
27
17
|
export async function readEmailTemplates(env) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/admin.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"admin.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/admin.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAkB5B,QAAA,MAAM,WAAW,4EAAa,CAAC;AA6B/B,eAAe,WAAW,CAAC"}
|
|
@@ -2,17 +2,15 @@
|
|
|
2
2
|
* Admin Routes for Email Module — D1-backed, no Plunk
|
|
3
3
|
*/
|
|
4
4
|
import { Hono } from 'hono';
|
|
5
|
-
import {
|
|
6
|
-
import { authMiddleware } from '../../../middleware/auth';
|
|
5
|
+
import { authMiddleware, requirePermission } from '../../../middleware/auth';
|
|
7
6
|
// Subscribers
|
|
8
7
|
import { getSubscribers, createSubscriber, updateSubscriber, deleteSubscriber, } from '../handlers/subscribers.handler';
|
|
9
8
|
// Campaigns
|
|
10
9
|
import { getCampaigns, sendCampaign, testCampaign } from '../handlers/campaigns.handler';
|
|
11
10
|
// Transactional send
|
|
12
11
|
import { sendTransactional, sendBulkEmail } from '../handlers/send.handler';
|
|
13
|
-
import { previewInvoice } from '../../../lib/invoice';
|
|
14
12
|
const adminRoutes = new Hono();
|
|
15
|
-
adminRoutes.use('*', authMiddleware);
|
|
13
|
+
adminRoutes.use('*', authMiddleware, requirePermission('newsletter'));
|
|
16
14
|
// =============================================================================
|
|
17
15
|
// Subscribers
|
|
18
16
|
// =============================================================================
|
|
@@ -34,5 +32,4 @@ adminRoutes.post('/send/bulk', sendBulkEmail);
|
|
|
34
32
|
// =============================================================================
|
|
35
33
|
// Invoice preview
|
|
36
34
|
// =============================================================================
|
|
37
|
-
adminRoutes.post('/invoices/preview', bodyLimit({ maxSize: 8 * 1024 * 1024 }), previewInvoice);
|
|
38
35
|
export default adminRoutes;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mail.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/mail.routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAM9C,QAAA,MAAM,MAAM,sDAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"mail.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/mail.routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAM9C,QAAA,MAAM,MAAM,sDAAsB,CAAC;AAwLnC,eAAe,MAAM,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
2
|
import { bodyLimit } from 'hono/body-limit';
|
|
3
|
-
import { authMiddleware } from '../../../middleware/auth';
|
|
3
|
+
import { authMiddleware, requirePermission } from '../../../middleware/auth';
|
|
4
4
|
import { createId, ensureSchema } from '../../../lib/project-db';
|
|
5
5
|
import { validEmail } from '../../../lib/user-recovery';
|
|
6
6
|
import { publicMessage, processOutbox } from '../../../lib/mail';
|
|
@@ -14,21 +14,26 @@ routes.use('*', async (c, next) => {
|
|
|
14
14
|
return c.json({ error: 'Cross-origin mail access is not allowed' }, 403);
|
|
15
15
|
await next();
|
|
16
16
|
});
|
|
17
|
-
routes.use('*', authMiddleware, bodyLimit({ maxSize: 6 * 1024 * 1024 }));
|
|
17
|
+
routes.use('*', authMiddleware, requirePermission('mail'), bodyLimit({ maxSize: 6 * 1024 * 1024 }));
|
|
18
18
|
routes.use('*', async (c, next) => { c.header('Cache-Control', 'no-store'); await next(); });
|
|
19
19
|
routes.get('/mailboxes', async (c) => {
|
|
20
20
|
const db = await ensureSchema(c.env);
|
|
21
21
|
const { results } = await db.prepare(`SELECT m.*, (SELECT COUNT(*) FROM mail_messages e WHERE e.mailbox = m.address AND e.direction = 'inbound' AND e.read_at IS NULL AND e.archived_at IS NULL AND e.spam = 0) AS unread FROM mailboxes m ORDER BY address`).all();
|
|
22
|
-
return c.json({ mailboxes: results, storageConfigured: !!c.env.MAIL_STORAGE, sendingConfigured: !!(c.env.API_KEY || c.env.PLUNK_SECRET_KEY) });
|
|
22
|
+
return c.json({ mailboxes: results, storageConfigured: !!c.env.MAIL_STORAGE, sendingConfigured: !!(c.env.API_KEY || c.env.PLUNK_SECRET_KEY || c.env.DISABLE_DEPLOYMENTS === 'true') });
|
|
23
23
|
});
|
|
24
24
|
routes.post('/mailboxes', async (c) => {
|
|
25
25
|
const body = await c.req.json();
|
|
26
26
|
const address = typeof body.address === 'string' ? body.address.trim().toLowerCase() : '';
|
|
27
27
|
if (!validEmail(address))
|
|
28
28
|
return c.json({ error: 'Enter a valid mailbox address.' }, 400);
|
|
29
|
+
const forwardTo = typeof body.forwardTo === 'string' ? body.forwardTo.trim().toLowerCase() : '';
|
|
30
|
+
if (forwardTo && !validEmail(forwardTo))
|
|
31
|
+
return c.json({ error: 'Enter a valid forwarding address.' }, 400);
|
|
32
|
+
if (forwardTo === address)
|
|
33
|
+
return c.json({ error: 'A mailbox cannot forward to itself.' }, 400);
|
|
29
34
|
const db = await ensureSchema(c.env);
|
|
30
|
-
await db.prepare('INSERT INTO mailboxes (address, name, created_at) VALUES (?, ?, ?) ON CONFLICT(address) DO UPDATE SET name = excluded.name')
|
|
31
|
-
.bind(address, typeof body.name === 'string' ? body.name.trim().slice(0, 200) : address, Date.now()).run();
|
|
35
|
+
await db.prepare('INSERT INTO mailboxes (address, name, created_at, forward_to) VALUES (?, ?, ?, ?) ON CONFLICT(address) DO UPDATE SET name = excluded.name, forward_to = excluded.forward_to')
|
|
36
|
+
.bind(address, typeof body.name === 'string' ? body.name.trim().slice(0, 200) : address, Date.now(), forwardTo || null).run();
|
|
32
37
|
// Only one mailbox may hold the flag, so move it rather than adding a second.
|
|
33
38
|
if (body.catchAll === true) {
|
|
34
39
|
await db.batch([
|
|
@@ -38,10 +43,16 @@ routes.post('/mailboxes', async (c) => {
|
|
|
38
43
|
}
|
|
39
44
|
return c.json({ success: true });
|
|
40
45
|
});
|
|
46
|
+
routes.delete('/mailboxes/:address', async (c) => {
|
|
47
|
+
const address = decodeURIComponent(c.req.param('address')).trim().toLowerCase();
|
|
48
|
+
const db = await ensureSchema(c.env);
|
|
49
|
+
await db.prepare('DELETE FROM mailboxes WHERE address = ?').bind(address).run();
|
|
50
|
+
return c.json({ success: true });
|
|
51
|
+
});
|
|
41
52
|
const folders = {
|
|
42
53
|
inbox: "direction = 'inbound' AND archived_at IS NULL AND spam = 0",
|
|
43
|
-
sent: "direction = 'outbound' AND status
|
|
44
|
-
drafts: "status = 'draft'",
|
|
54
|
+
sent: "direction = 'outbound' AND status <> 'draft'",
|
|
55
|
+
drafts: "status = 'draft'",
|
|
45
56
|
archive: 'archived_at IS NOT NULL AND spam = 0', spam: 'spam = 1',
|
|
46
57
|
};
|
|
47
58
|
routes.get('/messages', async (c) => {
|
|
@@ -52,8 +63,9 @@ routes.get('/messages', async (c) => {
|
|
|
52
63
|
const search = (c.req.query('q') || '').slice(0, 200);
|
|
53
64
|
const mailbox = c.req.query('mailbox') || '';
|
|
54
65
|
const offset = Math.max(0, Math.min(100000, Number(c.req.query('offset')) || 0));
|
|
55
|
-
const { results } = await db.prepare(`SELECT * FROM
|
|
56
|
-
AND (? = '' OR mailbox = ?) AND (? = '' OR instr(lower(subject || ' ' || sender || ' ' || recipient || ' ' || body_text), lower(?)) > 0)
|
|
66
|
+
const { results } = await db.prepare(`SELECT * FROM mail_messages WHERE ${folder}
|
|
67
|
+
AND (? = '' OR mailbox = ?) AND (? = '' OR instr(lower(subject || ' ' || sender || ' ' || recipient || ' ' || body_text), lower(?)) > 0)
|
|
68
|
+
ORDER BY created_at DESC, id DESC LIMIT 51 OFFSET ?`)
|
|
57
69
|
.bind(mailbox, mailbox, search, search, offset).all();
|
|
58
70
|
return c.json({ messages: results.slice(0, 50).map(row => ({ ...publicMessage(row), body_text: row.body_text.slice(0, 180) })), hasMore: results.length > 50 });
|
|
59
71
|
});
|
|
@@ -62,9 +74,20 @@ routes.get('/messages/:id', async (c) => {
|
|
|
62
74
|
const row = await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first();
|
|
63
75
|
if (!row)
|
|
64
76
|
return c.json({ error: 'Message not found.' }, 404);
|
|
65
|
-
|
|
66
|
-
return c.json({ messages: results.map(publicMessage) });
|
|
77
|
+
return c.json({ message: publicMessage(row), messages: [publicMessage(row)] });
|
|
67
78
|
});
|
|
79
|
+
function formatReplyQuote(parent) {
|
|
80
|
+
const d = new Date(parent.created_at);
|
|
81
|
+
const dateStr = d.toLocaleString('de-DE', {
|
|
82
|
+
weekday: 'long',
|
|
83
|
+
day: 'numeric',
|
|
84
|
+
month: 'long',
|
|
85
|
+
year: 'numeric',
|
|
86
|
+
hour: '2-digit',
|
|
87
|
+
minute: '2-digit'
|
|
88
|
+
});
|
|
89
|
+
return `\n\n\n________________________________\nVon: ${parent.sender}\nGesendet: ${dateStr}\nAn: ${parent.recipient}\nBetreff: ${parent.subject || ''}\n\n${parent.body_text || ''}`;
|
|
90
|
+
}
|
|
68
91
|
routes.post('/drafts', async (c) => {
|
|
69
92
|
const body = await c.req.json();
|
|
70
93
|
const db = await ensureSchema(c.env);
|
|
@@ -77,9 +100,10 @@ routes.post('/drafts', async (c) => {
|
|
|
77
100
|
const id = createId('mail');
|
|
78
101
|
const now = Date.now();
|
|
79
102
|
const refs = parent ? [...JSON.parse(parent.references_json), ...(parent.message_id ? [parent.message_id] : [])].slice(-10) : [];
|
|
103
|
+
const bodyText = parent ? formatReplyQuote(parent) : '';
|
|
80
104
|
await db.prepare(`INSERT INTO mail_messages (id, thread_id, mailbox, direction, status, sender, recipient, subject, body_text, message_id, in_reply_to, references_json, created_at, updated_at)
|
|
81
|
-
VALUES (?, ?, ?, 'outbound', 'draft', ?, ?, ?,
|
|
82
|
-
.bind(id, parent?.thread_id || id, mailbox, mailbox, parent ? parent.direction === 'inbound' ? parent.reply_address || parent.sender : parent.recipient : '', parent ? /^re:/i.test(parent.subject) ? parent.subject : `Re: ${parent.subject}` : '', `<${id}@${mailbox.split('@')[1]}>`, parent?.message_id || null, JSON.stringify(refs), now, now).run();
|
|
105
|
+
VALUES (?, ?, ?, 'outbound', 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
106
|
+
.bind(id, parent?.thread_id || id, mailbox, mailbox, parent ? parent.direction === 'inbound' ? parent.reply_address || parent.sender : parent.recipient : '', parent ? /^re:/i.test(parent.subject) ? parent.subject : `Re: ${parent.subject}` : '', bodyText, `<${id}@${mailbox.split('@')[1]}>`, parent?.message_id || null, JSON.stringify(refs), now, now).run();
|
|
83
107
|
return c.json({ message: publicMessage((await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(id).first())) }, 201);
|
|
84
108
|
});
|
|
85
109
|
routes.put('/drafts/:id', async (c) => {
|
|
@@ -128,7 +152,7 @@ routes.post('/drafts/:id/send', async (c) => {
|
|
|
128
152
|
return c.json({ error: 'Draft changed or already queued.' }, 409);
|
|
129
153
|
if (!validEmail(row.recipient) || !row.subject.trim() || !row.body_text.trim())
|
|
130
154
|
return c.json({ error: 'Recipient, subject and message are required.' }, 400);
|
|
131
|
-
if (!(c.env.API_KEY || c.env.PLUNK_SECRET_KEY))
|
|
155
|
+
if (!(c.env.API_KEY || c.env.PLUNK_SECRET_KEY || c.env.DISABLE_DEPLOYMENTS === 'true'))
|
|
132
156
|
return c.json({ error: 'Configure the Plunk sending integration first.' }, 503);
|
|
133
157
|
const now = Date.now();
|
|
134
158
|
const result = await db.prepare("UPDATE mail_messages SET status = 'queued', next_attempt_at = ?, updated_at = ?, created_at = ? WHERE id = ? AND status = 'draft' AND updated_at = ?")
|
|
@@ -149,10 +173,32 @@ routes.delete('/drafts/:id', async (c) => {
|
|
|
149
173
|
await c.env.MAIL_STORAGE.delete(attachments.map(a => a.key));
|
|
150
174
|
return c.json({ success: true });
|
|
151
175
|
});
|
|
176
|
+
routes.delete('/messages/:id', async (c) => {
|
|
177
|
+
const db = await ensureSchema(c.env);
|
|
178
|
+
const row = await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first();
|
|
179
|
+
if (!row)
|
|
180
|
+
return c.json({ error: 'Message not found.' }, 404);
|
|
181
|
+
if (c.env.MAIL_STORAGE) {
|
|
182
|
+
const keys = [];
|
|
183
|
+
if (row.raw_key)
|
|
184
|
+
keys.push(row.raw_key);
|
|
185
|
+
const atts = JSON.parse(row.attachments_json || '[]');
|
|
186
|
+
for (const a of atts)
|
|
187
|
+
keys.push(a.key);
|
|
188
|
+
if (keys.length) {
|
|
189
|
+
try {
|
|
190
|
+
await c.env.MAIL_STORAGE.delete(keys);
|
|
191
|
+
}
|
|
192
|
+
catch { }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
await db.prepare('DELETE FROM mail_messages WHERE id = ?').bind(row.id).run();
|
|
196
|
+
return c.json({ success: true });
|
|
197
|
+
});
|
|
152
198
|
routes.patch('/messages/:id', async (c) => {
|
|
153
199
|
const body = await c.req.json();
|
|
154
200
|
const db = await ensureSchema(c.env);
|
|
155
|
-
const row = await db.prepare('SELECT
|
|
201
|
+
const row = await db.prepare('SELECT id FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first();
|
|
156
202
|
if (!row)
|
|
157
203
|
return c.json({ error: 'Message not found.' }, 404);
|
|
158
204
|
const updates = [];
|
|
@@ -165,7 +211,7 @@ routes.patch('/messages/:id', async (c) => {
|
|
|
165
211
|
}
|
|
166
212
|
if (!updates.length)
|
|
167
213
|
return c.json({ error: 'No changes.' }, 400);
|
|
168
|
-
await db.prepare(`UPDATE mail_messages SET ${updates.join(', ')} WHERE
|
|
214
|
+
await db.prepare(`UPDATE mail_messages SET ${updates.join(', ')} WHERE id = ?`).bind(...args, row.id).run();
|
|
169
215
|
return c.json({ success: true });
|
|
170
216
|
});
|
|
171
217
|
routes.get('/messages/:id/files/:index', async (c) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/public.handler.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/public.handler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAsO/C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAY7F;AAED,wBAAsB,qBAAqB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiGjG;AAED,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoBrF;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAc1F;AAED,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAUzF;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqB7F;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmB1F;AAmHD,wBAAsB,oBAAoB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAehG;AAED,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAY5F;AAED,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4B/F"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
+
import { escapeHtml } from '../../../lib/user-recovery';
|
|
1
2
|
import { getEmailsConfig } from '../../../lib/config';
|
|
2
3
|
import Stripe from 'stripe';
|
|
3
4
|
import { renderInvoice } from '../../../lib/invoice';
|
|
4
5
|
import { base64 } from '../../../lib/design';
|
|
5
6
|
import { assertEmailConfigured, sendEmail } from '../../../lib/email';
|
|
6
|
-
import {
|
|
7
|
+
import { renderEmail } from '@hintergrund/runtime-contracts';
|
|
7
8
|
import { readShopCatalog, readShopSettings } from './products.handler';
|
|
8
|
-
import {
|
|
9
|
+
import { readEmailLayout, readEmailTemplates } from '../../emails/handlers/settings.handler';
|
|
9
10
|
import { ensureSchema } from '../../../lib/project-db';
|
|
10
11
|
const EUROPEAN_STRIPE_COUNTRIES = [
|
|
11
12
|
'AL', 'AD', 'AT', 'BY', 'BE', 'BA', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE',
|
|
@@ -379,7 +380,7 @@ async function sendInvoiceEmail(env, order, bankInstructions) {
|
|
|
379
380
|
if (!emailsConfig)
|
|
380
381
|
throw new Error('Configure email delivery before sending invoices.');
|
|
381
382
|
assertEmailConfigured(env);
|
|
382
|
-
const
|
|
383
|
+
const layout = await readEmailLayout(env);
|
|
383
384
|
const { settings: shopSettings } = await readShopSettings(env);
|
|
384
385
|
order.invoiceNumber ||= numberWithPrefix(shopSettings.invoiceNumberPrefix);
|
|
385
386
|
const invoiceData = orderToInvoiceData(order);
|
|
@@ -390,25 +391,24 @@ async function sendInvoiceEmail(env, order, bankInstructions) {
|
|
|
390
391
|
const subject = applyTemplateVars(purchase.subject, vars);
|
|
391
392
|
let htmlBody = applyTemplateVars(purchase.bodyHtml, vars);
|
|
392
393
|
if (bankInstructions) {
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
394
|
+
const rows = [
|
|
395
|
+
['Amount', formattedAmount],
|
|
396
|
+
['Account holder', bankInstructions.accountHolder],
|
|
397
|
+
['IBAN', bankInstructions.iban],
|
|
398
|
+
['BIC', bankInstructions.bic],
|
|
399
|
+
['Bank', bankInstructions.bankName],
|
|
400
|
+
['Reference', bankInstructions.reference],
|
|
397
401
|
];
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
lines.push(`Reference: ${bankInstructions.reference}`);
|
|
403
|
-
if (bankInstructions.instructions)
|
|
404
|
-
lines.push(`\n${bankInstructions.instructions}`);
|
|
405
|
-
htmlBody = `${htmlBody}\n\n${lines.join('\n')}`;
|
|
402
|
+
const table = rows.filter((row) => !!row[1])
|
|
403
|
+
.map(([label, value]) => `<tr><td style="padding:4px 16px 4px 0;opacity:.7;">${label}</td><td style="padding:4px 0;font-weight:600;">${escapeHtml(value)}</td></tr>`).join('');
|
|
404
|
+
const note = bankInstructions.instructions ? `<p style="margin:12px 0 0;">${escapeHtml(bankInstructions.instructions).replaceAll('\n', '<br>')}</p>` : '';
|
|
405
|
+
htmlBody += `<div style="margin:24px 0 0;padding:20px;border:1px solid rgba(127,127,127,.25);border-radius:8px;"><p style="margin:0 0 12px;font-weight:600;">Payment by bank transfer</p><table role="presentation" style="border-collapse:collapse;font-size:14px;">${table}</table>${note}</div>`;
|
|
406
406
|
}
|
|
407
407
|
await sendEmail(env, {
|
|
408
408
|
to: order.customer.email,
|
|
409
409
|
toName: order.customer.name ?? undefined,
|
|
410
410
|
subject,
|
|
411
|
-
html:
|
|
411
|
+
html: renderEmail(layout, htmlBody),
|
|
412
412
|
attachments: [{ filename: `${(order.invoiceNumber ?? order.orderNumber ?? 'invoice').replace(/[^a-zA-Z0-9_-]/g, '_')}.pdf`, content: base64(pdfBytes), contentType: 'application/pdf', disposition: 'attachment' }],
|
|
413
413
|
});
|
|
414
414
|
order.invoiceSentAt = Date.now();
|
|
@@ -418,7 +418,7 @@ async function sendPaymentConfirmationEmail(env, order) {
|
|
|
418
418
|
const emailsConfig = await tryGetEmailsConfig(env);
|
|
419
419
|
if (!emailsConfig)
|
|
420
420
|
return;
|
|
421
|
-
const [
|
|
421
|
+
const [layout, { payment_confirmed: template }] = await Promise.all([readEmailLayout(env), readEmailTemplates(env)]);
|
|
422
422
|
const amount = new Intl.NumberFormat('en-US', {
|
|
423
423
|
style: 'currency',
|
|
424
424
|
currency: order.totals.currency.toUpperCase()
|
|
@@ -431,7 +431,7 @@ async function sendPaymentConfirmationEmail(env, order) {
|
|
|
431
431
|
to: order.customer.email,
|
|
432
432
|
toName: order.customer.name ?? undefined,
|
|
433
433
|
subject,
|
|
434
|
-
html:
|
|
434
|
+
html: renderEmail(layout, html),
|
|
435
435
|
});
|
|
436
436
|
}
|
|
437
437
|
catch (error) {
|
package/dist/api/shop/routes.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
-
import { authMiddleware } from '../../middleware/auth';
|
|
2
|
+
import { authMiddleware, requirePermission } from '../../middleware/auth';
|
|
3
3
|
// Import handlers
|
|
4
4
|
import { getPublicProducts, createCheckoutSession, getOrders, getAdminOrder, getPublicOrder, updateOrderStatus, confirmPayment, generateOrderInvoice, sendOrderInvoice, handleStripeWebhook } from './handlers/public.handler';
|
|
5
5
|
const shopRoutes = new Hono();
|
|
@@ -9,7 +9,7 @@ shopRoutes.post('/checkout', createCheckoutSession);
|
|
|
9
9
|
shopRoutes.get('/orders/:id', getPublicOrder);
|
|
10
10
|
shopRoutes.post('/webhook', handleStripeWebhook);
|
|
11
11
|
// Apply auth middleware to all shop admin routes
|
|
12
|
-
shopRoutes.use('/admin/*', authMiddleware);
|
|
12
|
+
shopRoutes.use('/admin/*', authMiddleware, requirePermission('shop'));
|
|
13
13
|
// Orders
|
|
14
14
|
shopRoutes.get('/admin/orders', getOrders);
|
|
15
15
|
shopRoutes.get('/admin/orders/:id', getAdminOrder);
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
2
|
import { receiveEmail } from './lib/mail';
|
|
3
|
+
import type { PermissionArea } from '@hintergrund/runtime-contracts';
|
|
3
4
|
export type Bindings = {
|
|
4
5
|
SECRET?: string;
|
|
5
6
|
SETUP_TOKEN?: string;
|
|
@@ -36,6 +37,7 @@ export type Variables = {
|
|
|
36
37
|
userId?: string;
|
|
37
38
|
email?: string;
|
|
38
39
|
name?: string | null;
|
|
40
|
+
permissions?: PermissionArea[];
|
|
39
41
|
};
|
|
40
42
|
};
|
|
41
43
|
export type HonoEnv = {
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,EAAE,YAAY,EAAiB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,EAAE,YAAY,EAAiB,MAAM,YAAY,CAAC;AAGzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAMrE,MAAM,MAAM,QAAQ,GAAG;IAEtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,4EAA4E;IAC5E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAG7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAG1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,QAAQ,CAAC;IAGxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAG/B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAG1B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,OAAO,CAAC;IAChB,UAAU,CAAC,EAAE,UAAU,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACvB,IAAI,CAAC,EAAE;QACN,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,WAAW,CAAC,EAAE,cAAc,EAAE,CAAC;KAC/B,CAAC;CACF,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,SAAS,EAAE,SAAS,CAAA;CAAE,CAAC;AAEnE,wBAAgB,SAAS,yDAoGxB;AAED,iGAAiG;AACjG,wBAAgB,YAAY;;;2BAKG,mBAAmB,OAAO,QAAQ;EAEhE;AAGD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import emailRoutes from './api/emails/routes';
|
|
|
5
5
|
import mailRoutes from './api/emails/routes/mail.routes';
|
|
6
6
|
import { receiveEmail, processOutbox } from './lib/mail';
|
|
7
7
|
import shopRoutes from './api/shop/routes';
|
|
8
|
-
import { authMiddleware } from './middleware/auth';
|
|
8
|
+
import { authMiddleware, homeFor } from './middleware/auth';
|
|
9
9
|
import { getTemplate } from './lib/template';
|
|
10
10
|
import { hasValidSetupToken, projectNeedsSetup } from './api/cms/handlers/setup.handler';
|
|
11
11
|
export function createApp() {
|
|
@@ -58,12 +58,16 @@ export function createApp() {
|
|
|
58
58
|
if (!authPassed) {
|
|
59
59
|
return authResult;
|
|
60
60
|
}
|
|
61
|
+
const permissions = c.get('user')?.permissions ?? [];
|
|
62
|
+
if (!permissions.some((area) => area !== 'mail'))
|
|
63
|
+
return homeFor(permissions) ? c.redirect(homeFor(permissions)) : c.text('Your account has no access yet. Ask the project owner.', 403);
|
|
61
64
|
// Get admin configuration
|
|
62
65
|
try {
|
|
63
66
|
const { getAdminConfig } = await import('./lib/config');
|
|
64
67
|
const { activeAgentProvider } = await import('./api/cms/handlers/agent-provider.handler');
|
|
65
68
|
const adminConfig = getAdminConfig();
|
|
66
|
-
adminConfig.canManageAdminUsers =
|
|
69
|
+
adminConfig.canManageAdminUsers = permissions.includes('settings');
|
|
70
|
+
adminConfig.permissions = permissions;
|
|
67
71
|
adminConfig.integrations = {
|
|
68
72
|
stripeSecretKeySet: !!c.env.STRIPE_SECRET_KEY && c.env.STRIPE_SECRET_KEY !== 'NOT_CONFIGURED',
|
|
69
73
|
stripeWebhookSecretSet: !!c.env.STRIPE_WEBHOOK_SECRET && c.env.STRIPE_WEBHOOK_SECRET !== 'NOT_CONFIGURED',
|
|
@@ -79,18 +83,8 @@ export function createApp() {
|
|
|
79
83
|
return c.html(getTemplate('admin', c.env.UI_BASE_URL, configParams));
|
|
80
84
|
}
|
|
81
85
|
});
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
// not load the admin bundle. Authentication is the shared admin session.
|
|
85
|
-
app.get('/mail', async (c) => {
|
|
86
|
-
let authPassed = false;
|
|
87
|
-
const authResult = await authMiddleware(c, async () => {
|
|
88
|
-
authPassed = true;
|
|
89
|
-
});
|
|
90
|
-
if (!authPassed)
|
|
91
|
-
return authResult;
|
|
92
|
-
return c.html(getTemplate('mail', c.env.UI_BASE_URL));
|
|
93
|
-
});
|
|
86
|
+
// Mail client route: redirects to integrated admin mailbox
|
|
87
|
+
app.get('/mail', (c) => c.redirect('/admin#mail'));
|
|
94
88
|
// Serve static assets from the app build
|
|
95
89
|
app.get('*', async (c) => {
|
|
96
90
|
const url = new URL(c.req.url);
|
package/dist/lib/design.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { Bindings } from '../index';
|
|
2
|
-
export declare function readDesign(env: Bindings): Promise<import("@hintergrund/runtime-contracts").Design>;
|
|
3
2
|
export declare function readInvoiceDesign(env: Bindings): Promise<import("@hintergrund/runtime-contracts").InvoiceDesign>;
|
|
4
3
|
export declare function readDesignAsset(env: Bindings, path: string): Promise<Uint8Array>;
|
|
5
4
|
export declare function base64(bytes: Uint8Array): string;
|
package/dist/lib/design.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"design.d.ts","sourceRoot":"","sources":["../../src/lib/design.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,wBAAsB,
|
|
1
|
+
{"version":3,"file":"design.d.ts","sourceRoot":"","sources":["../../src/lib/design.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,mEAIpD;AACD,wBAAsB,eAAe,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAMtF;AACD,wBAAgB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIhD"}
|
package/dist/lib/design.js
CHANGED
|
@@ -1,14 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN, validateInvoiceDesign, publicAssetPath } from '@hintergrund/runtime-contracts';
|
|
2
2
|
import { createGitHubClient } from './github';
|
|
3
3
|
import { getGitHubConfig } from './config';
|
|
4
4
|
import { readJsonConfig } from './github-config';
|
|
5
|
-
export async function readDesign(env) {
|
|
6
|
-
const github = createGitHubClient(getGitHubConfig(env));
|
|
7
|
-
const file = await github.readJsonFileIfExists(DESIGN_PATH);
|
|
8
|
-
if (!file)
|
|
9
|
-
throw new Error(`Missing ${DESIGN_PATH}. Every website template ships one.`);
|
|
10
|
-
return validateDesign(file.data);
|
|
11
|
-
}
|
|
12
5
|
export async function readInvoiceDesign(env) {
|
|
13
6
|
const github = createGitHubClient(getGitHubConfig(env));
|
|
14
7
|
const { data } = await readJsonConfig(github, INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN);
|
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
3
|
-
bodyHtml: string;
|
|
4
|
-
/** Always derived from the project's design via emailTemplateFromDesign. */
|
|
5
|
-
template: EmailTemplateConfig;
|
|
6
|
-
/** Data URL of the letterhead chosen in email settings, if any. */
|
|
7
|
-
logoDataUrl?: string;
|
|
8
|
-
unsubscribeUrl?: string;
|
|
9
|
-
footerHtml?: string;
|
|
10
|
-
}
|
|
11
|
-
export type { EmailTemplateConfig } from '@hintergrund/runtime-contracts';
|
|
12
|
-
export declare function renderEmailTemplate(options: RenderEmailTemplateOptions): string;
|
|
1
|
+
/** The site's own unsubscribe page, which every newsletter site ships at `routes/emails/unsubscribe`. */
|
|
2
|
+
export declare function unsubscribeUrl(origin: string, email: string): string;
|
|
13
3
|
//# sourceMappingURL=email-template.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-template.d.ts","sourceRoot":"","sources":["../../src/lib/email-template.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"email-template.d.ts","sourceRoot":"","sources":["../../src/lib/email-template.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAEpE"}
|
|
@@ -1,36 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
function
|
|
3
|
-
return
|
|
4
|
-
}
|
|
5
|
-
function styleEmailBody(bodyHtml, primaryColor, headingFont) {
|
|
6
|
-
return bodyHtml
|
|
7
|
-
.replace(/<(h[1-4])([^>]*)>/gi, (match, tag, attributes) => {
|
|
8
|
-
if (/style=/i.test(attributes)) {
|
|
9
|
-
return match.replace(/style=(["'])(.*?)\1/i, `style=$1color:${primaryColor};font-family:${headingFont.replaceAll("'", '')};$2$1`);
|
|
10
|
-
}
|
|
11
|
-
return `<${tag}${attributes} style="color:${primaryColor};font-family:${headingFont};">`;
|
|
12
|
-
})
|
|
13
|
-
.replace(/<img([^>]*)>/gi, (match) => {
|
|
14
|
-
if (/style=/i.test(match))
|
|
15
|
-
return match;
|
|
16
|
-
return match.replace(/>$/, ' style="max-width:300px;display:block;margin:0 auto;height:auto;">');
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
export function renderEmailTemplate(options) {
|
|
20
|
-
const template = options.template;
|
|
21
|
-
const primaryColor = safeColor(template.primaryColor);
|
|
22
|
-
const bodyHtml = styleEmailBody(options.bodyHtml, primaryColor, template.headingFont);
|
|
23
|
-
const footerHtml = options.footerHtml ?? template.footerHtml ?? '';
|
|
24
|
-
const logoHtml = options.logoDataUrl
|
|
25
|
-
? `<div style="text-align:center;margin:0 0 20px 0;"><img src="${options.logoDataUrl}" alt="" style="max-width:120px;max-height:80px;height:auto;"></div>`
|
|
26
|
-
: '';
|
|
27
|
-
const unsubscribeHtml = options.unsubscribeUrl
|
|
28
|
-
? `<p style="margin:10px 0 0 0;"><a href="${options.unsubscribeUrl}" style="color:inherit;text-decoration:underline;">Unsubscribe</a></p>`
|
|
29
|
-
: '';
|
|
30
|
-
return template.html
|
|
31
|
-
.replaceAll('{{logo}}', logoHtml)
|
|
32
|
-
.replaceAll('{{content}}', bodyHtml)
|
|
33
|
-
.replaceAll('{{footer}}', footerHtml)
|
|
34
|
-
.replaceAll('{{unsubscribe}}', unsubscribeHtml)
|
|
35
|
-
.replaceAll('{{unsubscribe_url}}', options.unsubscribeUrl ?? '');
|
|
1
|
+
/** The site's own unsubscribe page, which every newsletter site ships at `routes/emails/unsubscribe`. */
|
|
2
|
+
export function unsubscribeUrl(origin, email) {
|
|
3
|
+
return `${origin}/emails/unsubscribe?email=${encodeURIComponent(email)}`;
|
|
36
4
|
}
|
package/dist/lib/email.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,MAAM,WAAW,eAAe;IAC/B,WAAW,CAAC,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,YAAY,GAAG,QAAQ,CAAA;KAAE,CAAC,CAAC;IACvH,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,qBAAa,kBAAmB,SAAQ,KAAK;IAC5C,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;gBACJ,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;CAI3C;AACD,MAAM,WAAW,YAAY;IAAG,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE;AAErD,0GAA0G;AAC1G,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,QAAQ,GAAG,MAAM,CAK3D;AAOD,wBAAsB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,YAAY,CAAC,CAe7F"}
|
package/dist/lib/email.js
CHANGED
|
@@ -13,10 +13,16 @@ export class EmailProviderError extends Error {
|
|
|
13
13
|
/** The provider key, or a message the owner can act on. Call before any slow work that ends in a send. */
|
|
14
14
|
export function assertEmailConfigured(env) {
|
|
15
15
|
const apiKey = env.API_KEY || env.PLUNK_SECRET_KEY;
|
|
16
|
+
if (!apiKey && localOutbox(env))
|
|
17
|
+
return '';
|
|
16
18
|
if (!apiKey)
|
|
17
19
|
throw new Error('Email delivery is not set up. Add an email provider key under Settings → Integrations.');
|
|
18
20
|
return apiKey;
|
|
19
21
|
}
|
|
22
|
+
/** Local development (DISABLE_DEPLOYMENTS) without a provider key logs mail instead of failing. */
|
|
23
|
+
function localOutbox(env) {
|
|
24
|
+
return env.DISABLE_DEPLOYMENTS === 'true' && !(env.API_KEY || env.PLUNK_SECRET_KEY);
|
|
25
|
+
}
|
|
20
26
|
export async function sendEmail(env, params) {
|
|
21
27
|
const apiKey = assertEmailConfigured(env);
|
|
22
28
|
const { settings } = await readEmailSettings(env);
|
|
@@ -24,7 +30,12 @@ export async function sendEmail(env, params) {
|
|
|
24
30
|
const fromName = params.fromName ?? settings.fromName ?? '';
|
|
25
31
|
const replyTo = params.replyTo ?? settings.replyTo;
|
|
26
32
|
if (!fromEmail)
|
|
27
|
-
throw new Error('No sender address is set. Add one under
|
|
33
|
+
throw new Error('No sender address is set. Add one under Settings → Emails.');
|
|
34
|
+
if (!apiKey) {
|
|
35
|
+
// The local harness has no provider key: print the message so links can be followed.
|
|
36
|
+
console.log(`[local mail] ${fromName} <${fromEmail}> → ${params.to}: ${params.subject}\n${[...params.html.matchAll(/href="([^"]+)"/g)].map(match => ` ${match[1]}`).join('\n')}`);
|
|
37
|
+
return {};
|
|
38
|
+
}
|
|
28
39
|
return sendViaPlunk(apiKey, fromEmail, fromName, { ...params, replyTo });
|
|
29
40
|
}
|
|
30
41
|
async function sendViaPlunk(apiKey, fromEmail, fromName, params) {
|
package/dist/lib/invoice.d.ts
CHANGED
|
@@ -1,13 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { type Design, type InvoiceDesign, type InvoiceData } from '@hintergrund/runtime-contracts';
|
|
1
|
+
import type { InvoiceData } from '@hintergrund/runtime-contracts';
|
|
3
2
|
import type { Bindings } from '../index';
|
|
4
|
-
export declare function renderInvoice(env: Bindings, data: InvoiceData
|
|
5
|
-
design: Design;
|
|
6
|
-
invoiceDesign: InvoiceDesign;
|
|
7
|
-
assets?: Partial<Record<'logo' | 'bodyFont' | 'displayFont', Uint8Array>>;
|
|
8
|
-
}): Promise<Uint8Array<ArrayBufferLike>>;
|
|
9
|
-
/** Authenticated, side-effect-free preview. Only presentation can be supplied. */
|
|
10
|
-
export declare function previewInvoice(c: Context<{
|
|
11
|
-
Bindings: Bindings;
|
|
12
|
-
}>): Promise<Response>;
|
|
3
|
+
export declare function renderInvoice(env: Bindings, data: InvoiceData): Promise<Uint8Array<ArrayBufferLike>>;
|
|
13
4
|
//# sourceMappingURL=invoice.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../src/lib/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../src/lib/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAElE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAIzC,wBAAsB,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,wCAInE"}
|