@hintergrund/worker 0.2.3 → 0.3.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/api/cms/handlers/admin-users.handler.d.ts +1 -0
- package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/admin-users.handler.js +60 -79
- package/dist/api/cms/handlers/auth.handler.d.ts +1 -1
- package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/auth.handler.js +13 -94
- package/dist/api/cms/handlers/dashboard.handler.d.ts +1 -1
- package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/dashboard.handler.js +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.js +8 -1
- package/dist/api/cms/handlers/integrations.handler.d.ts +5 -0
- package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/integrations.handler.js +24 -0
- package/dist/api/cms/handlers/recovery.handler.d.ts +5 -0
- package/dist/api/cms/handlers/recovery.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/recovery.handler.js +53 -0
- package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/setup.handler.js +142 -36
- package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -0
- package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-repo.handler.js +124 -16
- package/dist/api/cms/handlers/website-templates.handler.d.ts +2 -0
- package/dist/api/cms/handlers/website-templates.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-templates.handler.js +22 -2
- package/dist/api/cms/routes/auth.routes.d.ts +1 -1
- package/dist/api/cms/routes/auth.routes.d.ts.map +1 -1
- package/dist/api/cms/routes/auth.routes.js +7 -2
- package/dist/api/cms/routes/index.d.ts +1 -1
- package/dist/api/cms/routes/index.d.ts.map +1 -1
- package/dist/api/cms/routes/index.js +11 -8
- package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/campaigns.handler.js +3 -4
- package/dist/api/emails/handlers/invoice.handler.d.ts +8 -15
- package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/invoice.handler.js +142 -170
- package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/public.handler.js +27 -8
- package/dist/api/emails/handlers/send.handler.d.ts +1 -3
- package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/send.handler.js +18 -65
- package/dist/api/emails/handlers/settings.handler.d.ts +60 -12
- package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/settings.handler.js +38 -94
- package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/admin.routes.js +5 -6
- package/dist/api/emails/routes/mail-events.routes.d.ts +5 -0
- package/dist/api/emails/routes/mail-events.routes.d.ts.map +1 -0
- package/dist/api/emails/routes/mail-events.routes.js +29 -0
- package/dist/api/emails/routes/mail.routes.d.ts +5 -0
- package/dist/api/emails/routes/mail.routes.d.ts.map +1 -0
- package/dist/api/emails/routes/mail.routes.js +188 -0
- package/dist/api/shop/handlers/products.handler.d.ts +2 -2
- package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/products.handler.js +30 -8
- package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/public.handler.js +17 -66
- package/dist/index.d.ts +10 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26 -18
- package/dist/lib/brand.d.ts +6 -0
- package/dist/lib/brand.d.ts.map +1 -0
- package/dist/lib/brand.js +29 -0
- package/dist/lib/config.d.ts.map +1 -1
- package/dist/lib/config.js +1 -4
- package/dist/lib/email-template.d.ts +2 -5
- package/dist/lib/email-template.d.ts.map +1 -1
- package/dist/lib/email-template.js +6 -27
- package/dist/lib/email.d.ts +20 -11
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +29 -19
- package/dist/lib/github.d.ts +1 -1
- package/dist/lib/github.d.ts.map +1 -1
- package/dist/lib/github.js +13 -4
- package/dist/lib/integration-health.d.ts +18 -0
- package/dist/lib/integration-health.d.ts.map +1 -0
- package/dist/lib/integration-health.js +51 -0
- package/dist/lib/invoice.d.ts +13 -0
- package/dist/lib/invoice.d.ts.map +1 -0
- package/dist/lib/invoice.js +41 -0
- package/dist/lib/launch-draft.d.ts +14 -0
- package/dist/lib/launch-draft.d.ts.map +1 -0
- package/dist/lib/launch-draft.js +45 -0
- package/dist/lib/launch.d.ts +3 -0
- package/dist/lib/launch.d.ts.map +1 -0
- package/dist/lib/launch.js +18 -0
- package/dist/lib/mail-schema.d.ts +5 -0
- package/dist/lib/mail-schema.d.ts.map +1 -0
- package/dist/lib/mail-schema.js +62 -0
- package/dist/lib/mail.d.ts +83 -0
- package/dist/lib/mail.d.ts.map +1 -0
- package/dist/lib/mail.js +211 -0
- package/dist/lib/project-db.d.ts +3 -4
- package/dist/lib/project-db.d.ts.map +1 -1
- package/dist/lib/project-db.js +27 -42
- package/dist/lib/template-installer.d.ts +9 -0
- package/dist/lib/template-installer.d.ts.map +1 -0
- package/dist/lib/template-installer.js +97 -0
- package/dist/lib/template.d.ts.map +1 -1
- package/dist/lib/template.js +28 -0
- package/dist/lib/user-recovery.d.ts +9 -0
- package/dist/lib/user-recovery.d.ts.map +1 -0
- package/dist/lib/user-recovery.js +42 -0
- package/dist/lib/website-i18n.d.ts +10 -0
- package/dist/lib/website-i18n.d.ts.map +1 -0
- package/dist/lib/website-i18n.js +195 -0
- package/dist/middleware/auth.d.ts +3 -1
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +8 -4
- package/package.json +4 -2
- package/dist/hintergrund-assets.d.ts +0 -5
- package/dist/hintergrund-assets.d.ts.map +0 -1
- package/dist/hintergrund-assets.js +0 -11
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
3
|
+
import { authMiddleware } from '../../../middleware/auth';
|
|
4
|
+
import { createId, ensureSchema } from '../../../lib/project-db';
|
|
5
|
+
import { validEmail } from '../../../lib/user-recovery';
|
|
6
|
+
import { publicMessage, processOutbox } from '../../../lib/mail';
|
|
7
|
+
const routes = new Hono();
|
|
8
|
+
// Mailbox contents are the most sensitive reads in the project, so reject any
|
|
9
|
+
// cross-origin request outright rather than relying on CORS to hide the
|
|
10
|
+
// response after a cookie-authenticated handler has already run.
|
|
11
|
+
routes.use('*', async (c, next) => {
|
|
12
|
+
const origin = c.req.header('Origin');
|
|
13
|
+
if (origin && origin !== new URL(c.req.url).origin)
|
|
14
|
+
return c.json({ error: 'Cross-origin mail access is not allowed' }, 403);
|
|
15
|
+
await next();
|
|
16
|
+
});
|
|
17
|
+
routes.use('*', authMiddleware, bodyLimit({ maxSize: 6 * 1024 * 1024 }));
|
|
18
|
+
routes.use('*', async (c, next) => { c.header('Cache-Control', 'no-store'); await next(); });
|
|
19
|
+
routes.get('/mailboxes', async (c) => {
|
|
20
|
+
const db = await ensureSchema(c.env);
|
|
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) });
|
|
23
|
+
});
|
|
24
|
+
routes.post('/mailboxes', async (c) => {
|
|
25
|
+
const body = await c.req.json();
|
|
26
|
+
const address = typeof body.address === 'string' ? body.address.trim().toLowerCase() : '';
|
|
27
|
+
if (!validEmail(address))
|
|
28
|
+
return c.json({ error: 'Enter a valid mailbox address.' }, 400);
|
|
29
|
+
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();
|
|
32
|
+
// Only one mailbox may hold the flag, so move it rather than adding a second.
|
|
33
|
+
if (body.catchAll === true) {
|
|
34
|
+
await db.batch([
|
|
35
|
+
db.prepare('UPDATE mailboxes SET catch_all = 0 WHERE catch_all = 1 AND address <> ?').bind(address),
|
|
36
|
+
db.prepare('UPDATE mailboxes SET catch_all = 1 WHERE address = ?').bind(address),
|
|
37
|
+
]);
|
|
38
|
+
}
|
|
39
|
+
return c.json({ success: true });
|
|
40
|
+
});
|
|
41
|
+
const folders = {
|
|
42
|
+
inbox: "direction = 'inbound' AND archived_at IS NULL AND spam = 0",
|
|
43
|
+
sent: "direction = 'outbound' AND status IN ('accepted','delivered','bounced','complained')",
|
|
44
|
+
drafts: "status = 'draft'", outbox: "status IN ('queued','sending','failed','uncertain')",
|
|
45
|
+
archive: 'archived_at IS NOT NULL AND spam = 0', spam: 'spam = 1',
|
|
46
|
+
};
|
|
47
|
+
routes.get('/messages', async (c) => {
|
|
48
|
+
const db = await ensureSchema(c.env);
|
|
49
|
+
const folder = folders[c.req.query('folder') || 'inbox'];
|
|
50
|
+
if (!folder)
|
|
51
|
+
return c.json({ error: 'Unknown folder.' }, 400);
|
|
52
|
+
const search = (c.req.query('q') || '').slice(0, 200);
|
|
53
|
+
const mailbox = c.req.query('mailbox') || '';
|
|
54
|
+
const offset = Math.max(0, Math.min(100000, Number(c.req.query('offset')) || 0));
|
|
55
|
+
const { results } = await db.prepare(`SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY thread_id ORDER BY created_at DESC, id DESC) AS rank FROM mail_messages WHERE ${folder}
|
|
56
|
+
AND (? = '' OR mailbox = ?) AND (? = '' OR instr(lower(subject || ' ' || sender || ' ' || recipient || ' ' || body_text), lower(?)) > 0)) WHERE rank = 1 ORDER BY created_at DESC, id DESC LIMIT 51 OFFSET ?`)
|
|
57
|
+
.bind(mailbox, mailbox, search, search, offset).all();
|
|
58
|
+
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
|
+
});
|
|
60
|
+
routes.get('/messages/:id', async (c) => {
|
|
61
|
+
const db = await ensureSchema(c.env);
|
|
62
|
+
const row = await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first();
|
|
63
|
+
if (!row)
|
|
64
|
+
return c.json({ error: 'Message not found.' }, 404);
|
|
65
|
+
const { results } = await db.prepare('SELECT * FROM mail_messages WHERE thread_id = ? ORDER BY created_at ASC LIMIT 200').bind(row.thread_id).all();
|
|
66
|
+
return c.json({ messages: results.map(publicMessage) });
|
|
67
|
+
});
|
|
68
|
+
routes.post('/drafts', async (c) => {
|
|
69
|
+
const body = await c.req.json();
|
|
70
|
+
const db = await ensureSchema(c.env);
|
|
71
|
+
const mailbox = (body.mailbox || '').toLowerCase();
|
|
72
|
+
if (!await db.prepare('SELECT address FROM mailboxes WHERE address = ?').bind(mailbox).first())
|
|
73
|
+
return c.json({ error: 'Create a mailbox first.' }, 400);
|
|
74
|
+
const parent = body.replyTo ? await db.prepare('SELECT * FROM mail_messages WHERE id = ? AND mailbox = ?').bind(body.replyTo, mailbox).first() : null;
|
|
75
|
+
if (body.replyTo && !parent)
|
|
76
|
+
return c.json({ error: 'Reply target not found.' }, 404);
|
|
77
|
+
const id = createId('mail');
|
|
78
|
+
const now = Date.now();
|
|
79
|
+
const refs = parent ? [...JSON.parse(parent.references_json), ...(parent.message_id ? [parent.message_id] : [])].slice(-10) : [];
|
|
80
|
+
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();
|
|
83
|
+
return c.json({ message: publicMessage((await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(id).first())) }, 201);
|
|
84
|
+
});
|
|
85
|
+
routes.put('/drafts/:id', async (c) => {
|
|
86
|
+
const body = await c.req.json();
|
|
87
|
+
if (typeof body.recipient !== 'string' || typeof body.subject !== 'string' || typeof body.body_text !== 'string' || typeof body.version !== 'number'
|
|
88
|
+
|| body.recipient.length > 254 || body.subject.length > 998 || /[\r\n]/.test(body.subject) || body.body_text.length > 250000)
|
|
89
|
+
return c.json({ error: 'Invalid draft.' }, 400);
|
|
90
|
+
const db = await ensureSchema(c.env);
|
|
91
|
+
const result = await db.prepare("UPDATE mail_messages SET recipient = ?, subject = ?, body_text = ?, updated_at = ? WHERE id = ? AND status = 'draft' AND updated_at = ?")
|
|
92
|
+
.bind(body.recipient.trim().toLowerCase(), body.subject, body.body_text, Math.max(Date.now(), body.version + 1), c.req.param('id'), body.version).run();
|
|
93
|
+
if (!result.meta.changes)
|
|
94
|
+
return c.json({ error: 'Draft changed in another tab or was sent. Reload before editing.' }, 409);
|
|
95
|
+
return c.json({ message: publicMessage((await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first())) });
|
|
96
|
+
});
|
|
97
|
+
routes.post('/drafts/:id/attachments', async (c) => {
|
|
98
|
+
if (!c.env.MAIL_STORAGE)
|
|
99
|
+
return c.json({ error: 'MAIL_STORAGE is not configured.' }, 503);
|
|
100
|
+
const form = await c.req.formData();
|
|
101
|
+
const file = form.get('file');
|
|
102
|
+
const version = Number(form.get('version'));
|
|
103
|
+
if (!(file instanceof File) || file.size > 5 * 1024 * 1024 || !Number.isFinite(version))
|
|
104
|
+
return c.json({ error: 'Choose a file up to 5 MiB.' }, 400);
|
|
105
|
+
const db = await ensureSchema(c.env);
|
|
106
|
+
const row = await db.prepare("SELECT * FROM mail_messages WHERE id = ? AND status = 'draft'").bind(c.req.param('id')).first();
|
|
107
|
+
if (!row || row.updated_at !== version)
|
|
108
|
+
return c.json({ error: 'Draft changed. Reload first.' }, 409);
|
|
109
|
+
const attachments = JSON.parse(row.attachments_json);
|
|
110
|
+
if (attachments.length >= 10 || attachments.reduce((sum, a) => sum + a.size, 0) + file.size > 5 * 1024 * 1024)
|
|
111
|
+
return c.json({ error: 'Maximum 10 attachments / 5 MiB total.' }, 400);
|
|
112
|
+
const key = `mail/${row.id}/attachments/${crypto.randomUUID()}`;
|
|
113
|
+
await c.env.MAIL_STORAGE.put(key, file.stream());
|
|
114
|
+
attachments.push({ key, filename: file.name.slice(0, 200), contentType: file.type || 'application/octet-stream', size: file.size });
|
|
115
|
+
const result = await db.prepare("UPDATE mail_messages SET attachments_json = ?, updated_at = ? WHERE id = ? AND status = 'draft' AND updated_at = ?")
|
|
116
|
+
.bind(JSON.stringify(attachments), Math.max(Date.now(), version + 1), row.id, version).run();
|
|
117
|
+
if (!result.meta.changes) {
|
|
118
|
+
await c.env.MAIL_STORAGE.delete(key);
|
|
119
|
+
return c.json({ error: 'Draft changed. Reload first.' }, 409);
|
|
120
|
+
}
|
|
121
|
+
return c.json({ message: publicMessage((await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(row.id).first())) });
|
|
122
|
+
});
|
|
123
|
+
routes.post('/drafts/:id/send', async (c) => {
|
|
124
|
+
const { version } = await c.req.json();
|
|
125
|
+
const db = await ensureSchema(c.env);
|
|
126
|
+
const row = await db.prepare("SELECT * FROM mail_messages WHERE id = ? AND status = 'draft'").bind(c.req.param('id')).first();
|
|
127
|
+
if (!row || row.updated_at !== version)
|
|
128
|
+
return c.json({ error: 'Draft changed or already queued.' }, 409);
|
|
129
|
+
if (!validEmail(row.recipient) || !row.subject.trim() || !row.body_text.trim())
|
|
130
|
+
return c.json({ error: 'Recipient, subject and message are required.' }, 400);
|
|
131
|
+
if (!(c.env.API_KEY || c.env.PLUNK_SECRET_KEY))
|
|
132
|
+
return c.json({ error: 'Configure the Plunk sending integration first.' }, 503);
|
|
133
|
+
const now = Date.now();
|
|
134
|
+
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 = ?")
|
|
135
|
+
.bind(now, now, now, row.id, version).run();
|
|
136
|
+
if (!result.meta.changes)
|
|
137
|
+
return c.json({ error: 'Draft changed or already queued.' }, 409);
|
|
138
|
+
c.executionCtx.waitUntil(processOutbox(c.env));
|
|
139
|
+
return c.json({ success: true, message: 'Queued for sending.' }, 202);
|
|
140
|
+
});
|
|
141
|
+
routes.delete('/drafts/:id', async (c) => {
|
|
142
|
+
const db = await ensureSchema(c.env);
|
|
143
|
+
const version = Number(c.req.query('version'));
|
|
144
|
+
const row = await db.prepare("DELETE FROM mail_messages WHERE id = ? AND status = 'draft' AND updated_at = ? RETURNING *").bind(c.req.param('id'), version).first();
|
|
145
|
+
if (!row)
|
|
146
|
+
return c.json({ error: 'Draft changed or already queued.' }, 409);
|
|
147
|
+
const attachments = JSON.parse(row.attachments_json);
|
|
148
|
+
if (attachments.length && c.env.MAIL_STORAGE)
|
|
149
|
+
await c.env.MAIL_STORAGE.delete(attachments.map(a => a.key));
|
|
150
|
+
return c.json({ success: true });
|
|
151
|
+
});
|
|
152
|
+
routes.patch('/messages/:id', async (c) => {
|
|
153
|
+
const body = await c.req.json();
|
|
154
|
+
const db = await ensureSchema(c.env);
|
|
155
|
+
const row = await db.prepare('SELECT thread_id FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first();
|
|
156
|
+
if (!row)
|
|
157
|
+
return c.json({ error: 'Message not found.' }, 404);
|
|
158
|
+
const updates = [];
|
|
159
|
+
const args = [];
|
|
160
|
+
for (const [field, key] of [['read_at', 'read'], ['archived_at', 'archived'], ['spam', 'spam']]) {
|
|
161
|
+
if (typeof body[key] === 'boolean') {
|
|
162
|
+
updates.push(`${field} = ?`);
|
|
163
|
+
args.push(key === 'spam' ? Number(body[key]) : body[key] ? Date.now() : null);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (!updates.length)
|
|
167
|
+
return c.json({ error: 'No changes.' }, 400);
|
|
168
|
+
await db.prepare(`UPDATE mail_messages SET ${updates.join(', ')} WHERE thread_id = ?`).bind(...args, row.thread_id).run();
|
|
169
|
+
return c.json({ success: true });
|
|
170
|
+
});
|
|
171
|
+
routes.get('/messages/:id/files/:index', async (c) => {
|
|
172
|
+
const db = await ensureSchema(c.env);
|
|
173
|
+
const row = await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first();
|
|
174
|
+
if (!row)
|
|
175
|
+
return c.notFound();
|
|
176
|
+
const index = c.req.param('index');
|
|
177
|
+
const attachment = JSON.parse(row.attachments_json)[Number(index)];
|
|
178
|
+
const key = index === 'raw' ? row.raw_key : attachment?.key;
|
|
179
|
+
if (!key || !c.env.MAIL_STORAGE)
|
|
180
|
+
return c.notFound();
|
|
181
|
+
const object = await c.env.MAIL_STORAGE.get(key);
|
|
182
|
+
if (!object)
|
|
183
|
+
return c.notFound();
|
|
184
|
+
const filename = index === 'raw' ? 'original.eml' : attachment.filename;
|
|
185
|
+
return new Response(object.body, { headers: { 'Content-Type': 'application/octet-stream', 'X-Content-Type-Options': 'nosniff',
|
|
186
|
+
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename).replace(/'/g, '%27')}`, 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; sandbox" } });
|
|
187
|
+
});
|
|
188
|
+
export default routes;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
2
|
import type { Bindings } from '../../../index';
|
|
3
3
|
import type { ShopCatalog, ShopSettings } from '@hintergrund/runtime-contracts';
|
|
4
|
-
|
|
5
|
-
export
|
|
4
|
+
import { SHOP_PRODUCTS_PATH, SHOP_SETTINGS_PATH } from '@hintergrund/runtime-contracts';
|
|
5
|
+
export { SHOP_PRODUCTS_PATH, SHOP_SETTINGS_PATH };
|
|
6
6
|
export declare const DEFAULT_SHOP_SETTINGS: ShopSettings & {
|
|
7
7
|
emailTemplates: {
|
|
8
8
|
purchase: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"products.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/products.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"products.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/products.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAM/C,OAAO,KAAK,EAOX,WAAW,EAEX,YAAY,EAKZ,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACxF,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,CAAC;AAGlD,eAAO,MAAM,qBAAqB,EAAE,YAAY,GAAG;IAClD,cAAc,EAAE;QACf,QAAQ,EAAE;YAAE,OAAO,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAA;SAAE,CAAC;QAChD,gBAAgB,EAAE;YAAE,OAAO,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAA;SAAE,CAAC;KACxD,CAAC;CAyBF,CAAC;AA+BF,wBAAsB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,WAAW,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAIzG;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,YAAY,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAc5G;AA6DD,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAYvF;AAED,wBAAsB,UAAU,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAatF;AAED,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsBzF;AAED,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwBzF;AAED,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoBzF;AAED,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAavF;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkC1F"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { getGitHubConfig } from '../../../lib/config';
|
|
2
|
+
import { isLaunchPending } from '../../../lib/launch';
|
|
3
|
+
import { translateWebsiteFiles } from '../../../lib/website-i18n';
|
|
2
4
|
import { createGitHubClient } from '../../../lib/github';
|
|
3
5
|
import { ConfigConflictError, readJsonConfig, writeJsonConfig } from '../../../lib/github-config';
|
|
4
|
-
|
|
5
|
-
export
|
|
6
|
+
import { SHOP_PRODUCTS_PATH, SHOP_SETTINGS_PATH } from '@hintergrund/runtime-contracts';
|
|
7
|
+
export { SHOP_PRODUCTS_PATH, SHOP_SETTINGS_PATH };
|
|
6
8
|
export const DEFAULT_SHOP_SETTINGS = {
|
|
7
9
|
currency: 'eur',
|
|
8
10
|
enabledPaymentMethods: ['bank_transfer'],
|
|
@@ -72,15 +74,24 @@ export async function readShopSettings(env) {
|
|
|
72
74
|
});
|
|
73
75
|
return { settings: data, commitSha };
|
|
74
76
|
}
|
|
75
|
-
async function writeCatalog(github, catalog, message, expectedCommitSha) {
|
|
77
|
+
async function writeCatalog(github, catalog, message, expectedCommitSha, env) {
|
|
76
78
|
if (expectedCommitSha && !(await github.checkNoConflict(expectedCommitSha))) {
|
|
77
79
|
const error = new Error('Catalog changed upstream. Reload before publishing.');
|
|
78
80
|
error.status = 409;
|
|
79
81
|
throw error;
|
|
80
82
|
}
|
|
81
83
|
catalog.updatedAt = Date.now();
|
|
82
|
-
await github.
|
|
83
|
-
|
|
84
|
+
const revision = expectedCommitSha || await github.getCommitSha();
|
|
85
|
+
let files;
|
|
86
|
+
try {
|
|
87
|
+
files = await translateWebsiteFiles(github, [{ path: SHOP_PRODUCTS_PATH, content: JSON.stringify(catalog, null, 2) }], env, revision);
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
// The catalog write has not happened: surface the cause as retryable, like website saves.
|
|
91
|
+
error.status = 422;
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
return github.writeFilesAtomic(files, message, revision);
|
|
84
95
|
}
|
|
85
96
|
function normalizeProduct(body, existing) {
|
|
86
97
|
const timestamp = nowSeconds();
|
|
@@ -107,6 +118,9 @@ function normalizeProduct(body, existing) {
|
|
|
107
118
|
};
|
|
108
119
|
}
|
|
109
120
|
function conflictResponse(c, error) {
|
|
121
|
+
if (error?.status === 422) {
|
|
122
|
+
return c.json({ success: false, error: error.message }, 422);
|
|
123
|
+
}
|
|
110
124
|
if (error?.status !== 409)
|
|
111
125
|
return null;
|
|
112
126
|
return c.json({ success: false, error: error.message, code: 'conflict' }, 409);
|
|
@@ -140,6 +154,8 @@ export async function getProduct(c) {
|
|
|
140
154
|
}
|
|
141
155
|
}
|
|
142
156
|
export async function createProduct(c) {
|
|
157
|
+
if (await isLaunchPending(getGitHub(c)))
|
|
158
|
+
return c.json({ error: 'Edit products locally until the first launch.' }, 422);
|
|
143
159
|
try {
|
|
144
160
|
const github = getGitHub(c);
|
|
145
161
|
const body = await c.req.json();
|
|
@@ -149,7 +165,7 @@ export async function createProduct(c) {
|
|
|
149
165
|
return c.json({ success: false, error: 'Product id or slug already exists' }, 409);
|
|
150
166
|
}
|
|
151
167
|
catalog.products = [product, ...catalog.products];
|
|
152
|
-
const commitSha = await writeCatalog(github, catalog, `Create shop product ${product.name} [skip ci]`, body.commitSha);
|
|
168
|
+
const commitSha = await writeCatalog(github, catalog, `Create shop product ${product.name} [skip ci]`, body.commitSha, c.env);
|
|
153
169
|
const response = { success: true, product, commitSha };
|
|
154
170
|
return c.json(response, 201);
|
|
155
171
|
}
|
|
@@ -162,6 +178,8 @@ export async function createProduct(c) {
|
|
|
162
178
|
}
|
|
163
179
|
}
|
|
164
180
|
export async function updateProduct(c) {
|
|
181
|
+
if (await isLaunchPending(getGitHub(c)))
|
|
182
|
+
return c.json({ error: 'Edit products locally until the first launch.' }, 422);
|
|
165
183
|
try {
|
|
166
184
|
const github = getGitHub(c);
|
|
167
185
|
const productId = c.req.param('id');
|
|
@@ -175,7 +193,7 @@ export async function updateProduct(c) {
|
|
|
175
193
|
if (duplicate)
|
|
176
194
|
return c.json({ success: false, error: 'Product slug already exists' }, 409);
|
|
177
195
|
catalog.products[index] = product;
|
|
178
|
-
const commitSha = await writeCatalog(github, catalog, `Update shop product ${product.name} [skip ci]`, body.commitSha);
|
|
196
|
+
const commitSha = await writeCatalog(github, catalog, `Update shop product ${product.name} [skip ci]`, body.commitSha, c.env);
|
|
179
197
|
const response = { success: true, product, commitSha };
|
|
180
198
|
return c.json(response);
|
|
181
199
|
}
|
|
@@ -188,6 +206,8 @@ export async function updateProduct(c) {
|
|
|
188
206
|
}
|
|
189
207
|
}
|
|
190
208
|
export async function deleteProduct(c) {
|
|
209
|
+
if (await isLaunchPending(getGitHub(c)))
|
|
210
|
+
return c.json({ error: 'Edit products locally until the first launch.' }, 422);
|
|
191
211
|
try {
|
|
192
212
|
const github = getGitHub(c);
|
|
193
213
|
const productId = c.req.param('id');
|
|
@@ -197,7 +217,7 @@ export async function deleteProduct(c) {
|
|
|
197
217
|
catalog.products = catalog.products.filter((item) => item.id !== productId && item.slug !== productId);
|
|
198
218
|
if (catalog.products.length === before)
|
|
199
219
|
return c.json({ success: false, error: 'Product not found' }, 404);
|
|
200
|
-
const commitSha = await writeCatalog(github, catalog, `Delete shop product ${productId} [skip ci]`, commitShaParam);
|
|
220
|
+
const commitSha = await writeCatalog(github, catalog, `Delete shop product ${productId} [skip ci]`, commitShaParam, c.env);
|
|
201
221
|
const response = { success: true, message: 'Product deleted', commitSha };
|
|
202
222
|
return c.json(response);
|
|
203
223
|
}
|
|
@@ -225,6 +245,8 @@ export async function getSettings(c) {
|
|
|
225
245
|
}
|
|
226
246
|
}
|
|
227
247
|
export async function updateSettings(c) {
|
|
248
|
+
if (await isLaunchPending(getGitHub(c)))
|
|
249
|
+
return c.json({ error: 'Complete the launch checklist before pushing settings to GitHub.' }, 422);
|
|
228
250
|
try {
|
|
229
251
|
const github = getGitHub(c);
|
|
230
252
|
const body = await c.req.json();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/public.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/public.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AA2O/C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAa7F;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;AAkHD,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 { getEmailsConfig
|
|
2
|
-
import { createGitHubClient } from '../../../lib/github';
|
|
1
|
+
import { getEmailsConfig } from '../../../lib/config';
|
|
3
2
|
import Stripe from 'stripe';
|
|
4
|
-
import {
|
|
3
|
+
import { renderInvoice } from '../../../lib/invoice';
|
|
4
|
+
import { base64 } from '../../../lib/brand';
|
|
5
5
|
import { sendEmail } from '../../../lib/email';
|
|
6
|
+
import { DEFAULT_SHOP_EMAIL_TEMPLATES } from '@hintergrund/runtime-contracts';
|
|
6
7
|
import { renderEmailTemplate } from '../../../lib/email-template';
|
|
7
8
|
import { readShopCatalog, readShopSettings } from './products.handler';
|
|
8
|
-
import {
|
|
9
|
+
import { readEmailTemplateData } 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',
|
|
@@ -76,14 +77,6 @@ async function getOrderByStripeSession(env, sessionId) {
|
|
|
76
77
|
const row = await db.prepare('SELECT * FROM shop_orders WHERE stripe_session_id = ?').bind(sessionId).first();
|
|
77
78
|
return row ? rowToOrder(row) : null;
|
|
78
79
|
}
|
|
79
|
-
function uint8ToBase64(bytes) {
|
|
80
|
-
let binary = '';
|
|
81
|
-
const chunkSize = 0x8000;
|
|
82
|
-
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
83
|
-
binary += String.fromCharCode(...bytes.slice(i, i + chunkSize));
|
|
84
|
-
}
|
|
85
|
-
return btoa(binary);
|
|
86
|
-
}
|
|
87
80
|
function calculateItems(request, catalogProducts) {
|
|
88
81
|
return request.items.map((requestItem) => {
|
|
89
82
|
const product = catalogProducts.find((item) => item.id === requestItem.productId || item.slug === requestItem.slug);
|
|
@@ -366,7 +359,7 @@ function orderToInvoiceData(order) {
|
|
|
366
359
|
}
|
|
367
360
|
return {
|
|
368
361
|
invoiceNumber: order.invoiceNumber || order.orderNumber,
|
|
369
|
-
invoiceDate: new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }),
|
|
362
|
+
invoiceDate: new Date(order.createdAt * 1000).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }),
|
|
370
363
|
customerName: order.customer.name || order.customer.email,
|
|
371
364
|
customerEmail: order.customer.email,
|
|
372
365
|
customerAddress: order.customer.address,
|
|
@@ -389,18 +382,17 @@ async function tryGetEmailsConfig(env) {
|
|
|
389
382
|
async function sendInvoiceEmail(env, order, bankInstructions) {
|
|
390
383
|
const emailsConfig = await tryGetEmailsConfig(env);
|
|
391
384
|
if (!emailsConfig)
|
|
392
|
-
|
|
393
|
-
const { invoiceConfig, branding } = await loadInvoiceSettings(env);
|
|
385
|
+
throw new Error('Configure email delivery before sending invoices.');
|
|
394
386
|
const { settings, logoDataUrl } = await readEmailTemplateData(env);
|
|
395
387
|
const { settings: shopSettings } = await readShopSettings(env);
|
|
396
388
|
order.invoiceNumber ||= numberWithPrefix(shopSettings.invoiceNumberPrefix);
|
|
397
389
|
const invoiceData = orderToInvoiceData(order);
|
|
398
|
-
const pdfBytes = await
|
|
390
|
+
const pdfBytes = await renderInvoice(env, invoiceData);
|
|
399
391
|
const purchaseTemplate = shopSettings.emailTemplates?.purchase;
|
|
400
392
|
const formattedAmount = new Intl.NumberFormat('en-US', { style: 'currency', currency: order.totals.currency.toUpperCase() }).format(order.totals.total / 100);
|
|
401
393
|
const vars = { order_number: order.orderNumber, invoice_number: order.invoiceNumber ?? '', amount: formattedAmount };
|
|
402
|
-
let subject = applyTemplateVars(purchaseTemplate?.subject ||
|
|
403
|
-
let htmlBody = applyTemplateVars(purchaseTemplate?.bodyHtml ||
|
|
394
|
+
let subject = applyTemplateVars(purchaseTemplate?.subject || DEFAULT_SHOP_EMAIL_TEMPLATES.purchase.subject, vars);
|
|
395
|
+
let htmlBody = applyTemplateVars(purchaseTemplate?.bodyHtml || DEFAULT_SHOP_EMAIL_TEMPLATES.purchase.bodyHtml, vars);
|
|
404
396
|
if (bankInstructions) {
|
|
405
397
|
const lines = [
|
|
406
398
|
`Please transfer ${new Intl.NumberFormat('en-US', { style: 'currency', currency: order.totals.currency.toUpperCase() }).format(order.totals.total / 100)} to:`,
|
|
@@ -421,7 +413,9 @@ async function sendInvoiceEmail(env, order, bankInstructions) {
|
|
|
421
413
|
toName: order.customer.name ?? undefined,
|
|
422
414
|
subject,
|
|
423
415
|
html: renderEmailTemplate({ bodyHtml: htmlBody, template: settings.emailTemplate, logoDataUrl }),
|
|
416
|
+
attachments: [{ filename: `${(order.invoiceNumber ?? order.orderNumber ?? 'invoice').replace(/[^a-zA-Z0-9_-]/g, '_')}.pdf`, content: base64(pdfBytes), contentType: 'application/pdf', disposition: 'attachment' }],
|
|
424
417
|
});
|
|
418
|
+
order.invoiceSentAt = nowSeconds();
|
|
425
419
|
await updateOrder(env, order);
|
|
426
420
|
}
|
|
427
421
|
async function sendPaymentConfirmationEmail(env, order) {
|
|
@@ -436,8 +430,8 @@ async function sendPaymentConfirmationEmail(env, order) {
|
|
|
436
430
|
}).format(order.totals.total / 100);
|
|
437
431
|
const confirmTemplate = shopSettings.emailTemplates?.paymentConfirmed;
|
|
438
432
|
const vars = { order_number: order.orderNumber, amount };
|
|
439
|
-
const subject = applyTemplateVars(confirmTemplate?.subject ||
|
|
440
|
-
const html = applyTemplateVars(confirmTemplate?.bodyHtml ||
|
|
433
|
+
const subject = applyTemplateVars(confirmTemplate?.subject || DEFAULT_SHOP_EMAIL_TEMPLATES.paymentConfirmed.subject, vars);
|
|
434
|
+
const html = applyTemplateVars(confirmTemplate?.bodyHtml || DEFAULT_SHOP_EMAIL_TEMPLATES.paymentConfirmed.bodyHtml, vars);
|
|
441
435
|
try {
|
|
442
436
|
await sendEmail(env, {
|
|
443
437
|
to: order.customer.email,
|
|
@@ -450,58 +444,16 @@ async function sendPaymentConfirmationEmail(env, order) {
|
|
|
450
444
|
console.error('Failed to send payment confirmation email:', error);
|
|
451
445
|
}
|
|
452
446
|
}
|
|
453
|
-
function guessLogoMime(path) {
|
|
454
|
-
const ext = path.split('.').pop()?.toLowerCase();
|
|
455
|
-
if (ext === 'png')
|
|
456
|
-
return 'image/png';
|
|
457
|
-
if (ext === 'jpg' || ext === 'jpeg')
|
|
458
|
-
return 'image/jpeg';
|
|
459
|
-
if (ext === 'gif')
|
|
460
|
-
return 'image/gif';
|
|
461
|
-
if (ext === 'svg')
|
|
462
|
-
return 'image/svg+xml';
|
|
463
|
-
return 'image/png';
|
|
464
|
-
}
|
|
465
|
-
async function loadInvoiceSettings(env) {
|
|
466
|
-
try {
|
|
467
|
-
const { settings } = await readEmailSettings(env);
|
|
468
|
-
let logoDataUrl;
|
|
469
|
-
if (settings.logoPath) {
|
|
470
|
-
try {
|
|
471
|
-
const github = createGitHubClient(getGitHubConfig(env));
|
|
472
|
-
const file = await github.readFileBinary(settings.logoPath);
|
|
473
|
-
if (file)
|
|
474
|
-
logoDataUrl = `data:${guessLogoMime(settings.logoPath)};base64,${file.content}`;
|
|
475
|
-
}
|
|
476
|
-
catch (error) {
|
|
477
|
-
console.error('Failed to load logo from GitHub:', error);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
return {
|
|
481
|
-
invoiceConfig: settings.invoice,
|
|
482
|
-
branding: {
|
|
483
|
-
logo: logoDataUrl,
|
|
484
|
-
companyName: settings.invoice.companyName,
|
|
485
|
-
primaryColor: settings.invoice.primaryColor,
|
|
486
|
-
},
|
|
487
|
-
};
|
|
488
|
-
}
|
|
489
|
-
catch (error) {
|
|
490
|
-
console.error('Failed to load invoice settings from GitHub:', error);
|
|
491
|
-
}
|
|
492
|
-
return { invoiceConfig: {} };
|
|
493
|
-
}
|
|
494
447
|
export async function generateOrderInvoice(c) {
|
|
495
448
|
try {
|
|
496
449
|
const order = await getOrderById(c.env, c.req.param('id') ?? '');
|
|
497
450
|
if (!order)
|
|
498
451
|
return c.json({ success: false, error: 'Order not found' }, 404);
|
|
499
|
-
const
|
|
500
|
-
const pdfBytes = await generateInvoicePdf(invoiceConfig, orderToInvoiceData(order), branding);
|
|
452
|
+
const pdfBytes = await renderInvoice(c.env, orderToInvoiceData(order));
|
|
501
453
|
return new Response(pdfBytes, {
|
|
502
454
|
headers: {
|
|
503
455
|
'Content-Type': 'application/pdf',
|
|
504
|
-
'Content-Disposition': `attachment; filename="${order.invoiceNumber || order.orderNumber}.pdf"`
|
|
456
|
+
'Content-Disposition': `attachment; filename="${(order.invoiceNumber || order.orderNumber).replace(/[^a-zA-Z0-9_-]/g, '_')}.pdf"`
|
|
505
457
|
}
|
|
506
458
|
});
|
|
507
459
|
}
|
|
@@ -515,9 +467,8 @@ export async function sendOrderInvoice(c) {
|
|
|
515
467
|
const order = await getOrderById(c.env, c.req.param('id') ?? '');
|
|
516
468
|
if (!order)
|
|
517
469
|
return c.json({ success: false, error: 'Order not found' }, 404);
|
|
470
|
+
// sendInvoiceEmail marks the order as sent only after the provider accepted delivery.
|
|
518
471
|
await sendInvoiceEmail(c.env, order);
|
|
519
|
-
order.invoiceSentAt = nowSeconds();
|
|
520
|
-
await updateOrder(c.env, order);
|
|
521
472
|
return c.json({ success: true, order });
|
|
522
473
|
}
|
|
523
474
|
catch (error) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
+
import { receiveEmail } from './lib/mail';
|
|
2
3
|
export type Bindings = {
|
|
3
4
|
SECRET?: string;
|
|
4
5
|
SETUP_TOKEN?: string;
|
|
@@ -19,9 +20,11 @@ export type Bindings = {
|
|
|
19
20
|
FROM_NAME?: string;
|
|
20
21
|
REPLY_TO?: string;
|
|
21
22
|
PLUNK_SECRET_KEY?: string;
|
|
23
|
+
/** Canonical project origin for account recovery links. */
|
|
24
|
+
PUBLIC_ORIGIN?: string;
|
|
25
|
+
MAIL_STORAGE?: R2Bucket;
|
|
22
26
|
STRIPE_SECRET_KEY?: string;
|
|
23
27
|
STRIPE_WEBHOOK_SECRET?: string;
|
|
24
|
-
STRIPE_PUBLISHABLE_KEY?: string;
|
|
25
28
|
GEMINI_API_KEY?: string;
|
|
26
29
|
DEEPSEEK_API_KEY?: string;
|
|
27
30
|
TEMPLATE_REGISTRY_URL?: string;
|
|
@@ -41,6 +44,12 @@ export type HonoEnv = {
|
|
|
41
44
|
Variables: Variables;
|
|
42
45
|
};
|
|
43
46
|
export declare function createApp(): Hono<HonoEnv, import("hono/types").BlankSchema, "/">;
|
|
47
|
+
/** Project entrypoint with HTTP, incoming email and D1 outbox processing. No Durable Objects. */
|
|
48
|
+
export declare function createWorker(): {
|
|
49
|
+
fetch: (request: Request, env?: {} | Bindings | undefined, executionCtx?: import("hono").ExecutionContext) => Response | Promise<Response>;
|
|
50
|
+
email: typeof receiveEmail;
|
|
51
|
+
scheduled(_controller: ScheduledController, env: Bindings): Promise<void>;
|
|
52
|
+
};
|
|
44
53
|
export * from './lib/auth/jwt';
|
|
45
54
|
export * from './lib/auth/crypto';
|
|
46
55
|
export * from './lib/template';
|
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;
|
|
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;AAQzD,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,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,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;KACrB,CAAC;CACF,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,SAAS,EAAE,SAAS,CAAA;CAAE,CAAC;AAEnE,wBAAgB,SAAS,yDA0GxB;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
|
@@ -2,10 +2,11 @@ import { Hono } from 'hono';
|
|
|
2
2
|
import { cors } from 'hono/cors';
|
|
3
3
|
import cmsRoutes from './api/cms/routes';
|
|
4
4
|
import emailRoutes from './api/emails/routes';
|
|
5
|
+
import mailRoutes from './api/emails/routes/mail.routes';
|
|
6
|
+
import { receiveEmail, processOutbox } from './lib/mail';
|
|
5
7
|
import shopRoutes from './api/shop/routes';
|
|
6
8
|
import { authMiddleware } from './middleware/auth';
|
|
7
9
|
import { getTemplate } from './lib/template';
|
|
8
|
-
import { ensureSchema } from './lib/project-db';
|
|
9
10
|
import { hasValidSetupToken, projectNeedsSetup } from './api/cms/handlers/setup.handler';
|
|
10
11
|
export function createApp() {
|
|
11
12
|
const app = new Hono();
|
|
@@ -38,26 +39,13 @@ export function createApp() {
|
|
|
38
39
|
app.get('/login', async (c) => {
|
|
39
40
|
if (await projectNeedsSetup(c))
|
|
40
41
|
return c.redirect('/setup');
|
|
41
|
-
|
|
42
|
-
try {
|
|
43
|
-
if (c.env.PROJECT_DB) {
|
|
44
|
-
const db = await ensureSchema(c.env);
|
|
45
|
-
const methods = await db
|
|
46
|
-
.prepare('SELECT login_method, COUNT(*) AS count FROM admin_users WHERE disabled_at IS NULL GROUP BY login_method ORDER BY count DESC')
|
|
47
|
-
.all();
|
|
48
|
-
const loginMethod = methods.results?.[0]?.login_method === 'otp' ? 'otp' : 'password';
|
|
49
|
-
configParams = `config='${JSON.stringify({ loginMethod })}'`;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
console.error('Failed to load project login config:', error);
|
|
54
|
-
}
|
|
55
|
-
return c.html(getTemplate('login', c.env.UI_BASE_URL, configParams));
|
|
42
|
+
return c.html(getTemplate('login', c.env.UI_BASE_URL));
|
|
56
43
|
});
|
|
57
44
|
// Mount CMS routes under /api/admin
|
|
58
45
|
app.route('/api/admin', cmsRoutes);
|
|
59
46
|
// Mount email routes under /api/email
|
|
60
47
|
app.route('/api/email', emailRoutes);
|
|
48
|
+
app.route('/api/mail', mailRoutes);
|
|
61
49
|
// Mount shop routes under /api/shop
|
|
62
50
|
app.route('/api/shop', shopRoutes);
|
|
63
51
|
// Admin main page (protected)
|
|
@@ -77,7 +65,6 @@ export function createApp() {
|
|
|
77
65
|
const adminConfig = getAdminConfig();
|
|
78
66
|
adminConfig.canManageAdminUsers = true;
|
|
79
67
|
adminConfig.integrations = {
|
|
80
|
-
stripePublishableKeySet: !!c.env.STRIPE_PUBLISHABLE_KEY,
|
|
81
68
|
stripeSecretKeySet: !!c.env.STRIPE_SECRET_KEY && c.env.STRIPE_SECRET_KEY !== 'NOT_CONFIGURED',
|
|
82
69
|
stripeWebhookSecretSet: !!c.env.STRIPE_WEBHOOK_SECRET && c.env.STRIPE_WEBHOOK_SECRET !== 'NOT_CONFIGURED',
|
|
83
70
|
emailProviderApiKeySet: !!(c.env.API_KEY || c.env.PLUNK_SECRET_KEY),
|
|
@@ -88,10 +75,22 @@ export function createApp() {
|
|
|
88
75
|
}
|
|
89
76
|
catch (error) {
|
|
90
77
|
// Fallback to default config if parsing fails
|
|
91
|
-
const configParams = 'config=\'{
|
|
78
|
+
const configParams = 'config=\'{}\'';
|
|
92
79
|
return c.html(getTemplate('admin', c.env.UI_BASE_URL, configParams));
|
|
93
80
|
}
|
|
94
81
|
});
|
|
82
|
+
// Standalone mail client (protected). Live D1 correspondence for the project's
|
|
83
|
+
// domain addresses — no Git staging, no Save, no agent, so it deliberately does
|
|
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
|
+
});
|
|
95
94
|
// Serve static assets from the app build
|
|
96
95
|
app.get('*', async (c) => {
|
|
97
96
|
const url = new URL(c.req.url);
|
|
@@ -108,6 +107,15 @@ export function createApp() {
|
|
|
108
107
|
});
|
|
109
108
|
return app;
|
|
110
109
|
}
|
|
110
|
+
/** Project entrypoint with HTTP, incoming email and D1 outbox processing. No Durable Objects. */
|
|
111
|
+
export function createWorker() {
|
|
112
|
+
const app = createApp();
|
|
113
|
+
return {
|
|
114
|
+
fetch: app.fetch,
|
|
115
|
+
email: receiveEmail,
|
|
116
|
+
async scheduled(_controller, env) { await processOutbox(env); },
|
|
117
|
+
};
|
|
118
|
+
}
|
|
111
119
|
// Export individual utilities if needed
|
|
112
120
|
export * from './lib/auth/jwt';
|
|
113
121
|
export * from './lib/auth/crypto';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Bindings } from '../index';
|
|
2
|
+
export declare function readBrand(env: Bindings): Promise<import("@hintergrund/runtime-contracts").Brand>;
|
|
3
|
+
export declare function readInvoiceDesign(env: Bindings): Promise<import("@hintergrund/runtime-contracts").InvoiceDesign>;
|
|
4
|
+
export declare function readBrandAsset(env: Bindings, path: string): Promise<Uint8Array>;
|
|
5
|
+
export declare function base64(bytes: Uint8Array): string;
|
|
6
|
+
//# sourceMappingURL=brand.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"brand.d.ts","sourceRoot":"","sources":["../../src/lib/brand.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,wBAAsB,SAAS,CAAC,GAAG,EAAE,QAAQ,2DAI5C;AACD,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,mEAIpD;AACD,wBAAsB,cAAc,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAMrF;AACD,wBAAgB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIhD"}
|