@zabaca/zbc 0.6.0 → 0.6.2
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/package.json +1 -1
- package/templates/apps/inbox/public/index.html +273 -83
- package/templates/apps/inbox/registry.json +1 -1
- package/templates/apps/inbox/worker/inbox-do.ts +144 -6
- package/templates/apps/inbox/worker/index.ts +62 -5
- package/templates/infra/modules/cloudflare/index.ts +13 -3
- package/templates/infra/modules/cloudflare-email/index.ts +55 -12
package/package.json
CHANGED
|
@@ -5,57 +5,178 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
6
|
<title>{{PROJECT_NAME}} inbox</title>
|
|
7
7
|
<style>
|
|
8
|
-
|
|
8
|
+
/* Prose design system tokens (mirrored from packages/design-system/src/tokens.css;
|
|
9
|
+
the inbox UI is a self-contained static page, so no Tailwind pipeline). */
|
|
10
|
+
:root {
|
|
11
|
+
color-scheme: light dark;
|
|
12
|
+
--paper-0: #FBFAF7; --paper-1: #F4F2EC; --paper-2: #EAE6DC; --paper-3: #DCD6C7;
|
|
13
|
+
--ink-0: #14140F; --ink-1: #2D2C25; --ink-2: #5A584C; --ink-3: #8A8676; --ink-4: #B8B3A1;
|
|
14
|
+
--accent: #B8410E; --accent-soft: #E8D5C4; --accent-ink: #6B2308;
|
|
15
|
+
--positive: #2F6B3C; --critical: #A8321A;
|
|
16
|
+
--font-display: 'Iowan Old Style', 'Source Serif Pro', Georgia, 'Times New Roman', serif;
|
|
17
|
+
--font-ui: 'Inter Tight', -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
|
|
18
|
+
--font-mono: 'JetBrains Mono', 'SF Mono', Menlo, Consolas, monospace;
|
|
19
|
+
--dur-fast: 140ms; --ease: cubic-bezier(0.2, 0.6, 0.2, 1);
|
|
20
|
+
}
|
|
21
|
+
@media (prefers-color-scheme: dark) {
|
|
22
|
+
:root {
|
|
23
|
+
--paper-0: #14130E; --paper-1: #1C1B16; --paper-2: #25241D; --paper-3: #34322A;
|
|
24
|
+
--ink-0: #F2EFE6; --ink-1: #DDD8C9; --ink-2: #A8A290; --ink-3: #75705F; --ink-4: #4A463C;
|
|
25
|
+
--accent: #E26B3A; --accent-soft: #3A2418; --accent-ink: #F0A57E;
|
|
26
|
+
--positive: #6FAE7C; --critical: #E2674F;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
9
30
|
* { box-sizing: border-box; }
|
|
10
|
-
body {
|
|
11
|
-
|
|
12
|
-
|
|
31
|
+
html, body { height: 100%; }
|
|
32
|
+
body {
|
|
33
|
+
margin: 0;
|
|
34
|
+
font: 400 0.9375rem/1.5 var(--font-ui);
|
|
35
|
+
background: var(--paper-0);
|
|
36
|
+
color: var(--ink-1);
|
|
37
|
+
}
|
|
38
|
+
button {
|
|
39
|
+
font: 500 0.8125rem/1 var(--font-ui);
|
|
40
|
+
letter-spacing: 0.04em;
|
|
41
|
+
padding: 0.5rem 0.75rem;
|
|
42
|
+
border: 1px solid var(--ink-4);
|
|
43
|
+
border-radius: 2px;
|
|
44
|
+
background: transparent;
|
|
45
|
+
color: var(--ink-1);
|
|
46
|
+
cursor: pointer;
|
|
47
|
+
transition: background var(--dur-fast) var(--ease), border-color var(--dur-fast) var(--ease);
|
|
48
|
+
}
|
|
49
|
+
button:hover { background: var(--paper-2); }
|
|
50
|
+
button.primary { background: var(--accent); border-color: var(--accent); color: #FBFAF7; }
|
|
51
|
+
button.primary:hover { filter: brightness(1.08); background: var(--accent); }
|
|
52
|
+
button.danger { color: var(--critical); border-color: var(--critical); }
|
|
53
|
+
|
|
54
|
+
header {
|
|
55
|
+
display: flex; align-items: baseline; gap: 0.75rem;
|
|
56
|
+
padding: 0.75rem 1.5rem;
|
|
57
|
+
border-bottom: 2px solid var(--ink-0);
|
|
58
|
+
background: var(--paper-0);
|
|
59
|
+
}
|
|
60
|
+
header h1 { font: 600 1.375rem/1.1 var(--font-display); letter-spacing: -0.015em; margin: 0; color: var(--ink-0); }
|
|
61
|
+
header .domain { font: 400 0.8125rem/1 var(--font-mono); color: var(--ink-3); }
|
|
13
62
|
header .spacer { flex: 1; }
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
main { display: grid; grid-template-columns: minmax(
|
|
17
|
-
#list { overflow-y: auto; border-right: 1px solid var(--
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
.
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
63
|
+
header .actions { display: flex; gap: 0.5rem; align-self: center; }
|
|
64
|
+
|
|
65
|
+
main { display: grid; grid-template-columns: minmax(280px, 400px) 1fr; height: calc(100dvh - 56px); }
|
|
66
|
+
#list { overflow-y: auto; border-right: 1px solid var(--paper-3); background: var(--paper-0); }
|
|
67
|
+
#reader { overflow-y: auto; background: var(--paper-1); }
|
|
68
|
+
|
|
69
|
+
.thread {
|
|
70
|
+
padding: 0.75rem 1.5rem;
|
|
71
|
+
border-bottom: 1px solid var(--paper-3);
|
|
72
|
+
cursor: pointer;
|
|
73
|
+
transition: background var(--dur-fast) var(--ease);
|
|
74
|
+
}
|
|
75
|
+
.thread:hover { background: var(--paper-1); }
|
|
76
|
+
.thread.active { background: var(--paper-2); box-shadow: inset 2px 0 0 var(--accent); }
|
|
77
|
+
.thread .top { display: flex; align-items: baseline; gap: 0.5rem; }
|
|
78
|
+
.thread .who { font-weight: 600; color: var(--ink-0); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
|
|
79
|
+
.thread .when { font-size: 0.75rem; color: var(--ink-3); white-space: nowrap; }
|
|
80
|
+
.thread .subject { display: block; color: var(--ink-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
81
|
+
.thread .snippet {
|
|
82
|
+
color: var(--ink-3); font-size: 0.8125rem;
|
|
83
|
+
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
|
|
84
|
+
}
|
|
85
|
+
.badge {
|
|
86
|
+
font-size: 0.6875rem; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase;
|
|
87
|
+
padding: 0.125rem 0.375rem; border-radius: 2px;
|
|
88
|
+
}
|
|
89
|
+
.badge.count { background: var(--paper-2); color: var(--ink-2); }
|
|
90
|
+
.badge.sent { background: var(--accent-soft); color: var(--accent-ink); }
|
|
91
|
+
|
|
92
|
+
/* Conversation view */
|
|
93
|
+
.convo { max-width: 46rem; margin: 0 auto; padding: 1.5rem; }
|
|
94
|
+
.convo-head { display: flex; align-items: baseline; gap: 0.75rem; margin-bottom: 1.5rem; }
|
|
95
|
+
.convo-head h2 { font: 600 1.75rem/1.1 var(--font-display); letter-spacing: -0.015em; color: var(--ink-0); margin: 0; flex: 1; }
|
|
96
|
+
#back { display: none; }
|
|
97
|
+
|
|
98
|
+
.bubble {
|
|
99
|
+
background: var(--paper-0);
|
|
100
|
+
border: 1px solid var(--paper-3);
|
|
101
|
+
border-radius: 2px;
|
|
102
|
+
margin-bottom: 1rem;
|
|
103
|
+
}
|
|
104
|
+
.bubble.outbound { border-left: 2px solid var(--accent); background: var(--paper-1); }
|
|
105
|
+
.bubble .head {
|
|
106
|
+
display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.5rem;
|
|
107
|
+
padding: 0.75rem 1rem; cursor: pointer;
|
|
108
|
+
}
|
|
109
|
+
.bubble .head .who { font-weight: 600; color: var(--ink-0); }
|
|
110
|
+
.bubble .head .arrow { color: var(--ink-3); font-size: 0.8125rem; }
|
|
111
|
+
.bubble .head .when { margin-left: auto; font-size: 0.75rem; color: var(--ink-3); white-space: nowrap; }
|
|
112
|
+
.bubble .body { padding: 0 1rem 1rem; border-top: 1px solid var(--paper-2); padding-top: 0.75rem; }
|
|
113
|
+
.bubble.collapsed .body, .bubble.collapsed .tools { display: none; }
|
|
114
|
+
.bubble.collapsed .head .preview { color: var(--ink-3); font-size: 0.8125rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 24rem; }
|
|
115
|
+
.bubble pre { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; margin: 0; color: var(--ink-1); }
|
|
116
|
+
.bubble iframe { width: 100%; min-height: 20rem; border: 1px solid var(--paper-3); border-radius: 2px; background: #fff; }
|
|
117
|
+
.bubble .tools { display: flex; gap: 0.5rem; padding: 0 1rem 0.75rem; }
|
|
118
|
+
.bubble .tools button { font-size: 0.6875rem; padding: 0.25rem 0.5rem; color: var(--ink-2); }
|
|
119
|
+
|
|
120
|
+
.reply-bar { display: flex; gap: 0.5rem; margin-top: 0.5rem; }
|
|
121
|
+
|
|
122
|
+
dialog {
|
|
123
|
+
border: 1px solid var(--paper-3); border-radius: 2px;
|
|
124
|
+
background: var(--paper-0); color: var(--ink-1);
|
|
125
|
+
padding: 1.5rem; width: min(560px, 92vw);
|
|
126
|
+
}
|
|
127
|
+
dialog::backdrop { background: rgba(20, 20, 15, 0.5); }
|
|
128
|
+
dialog h3 { font: 600 1.375rem/1.1 var(--font-display); color: var(--ink-0); margin: 0 0 1rem; }
|
|
129
|
+
form.compose { display: grid; gap: 0.5rem; }
|
|
130
|
+
form.compose input, form.compose textarea {
|
|
131
|
+
font: inherit; padding: 0.5rem 0.625rem;
|
|
132
|
+
border: 1px solid var(--ink-4); border-radius: 2px;
|
|
133
|
+
background: var(--paper-0); color: var(--ink-1); width: 100%;
|
|
134
|
+
}
|
|
135
|
+
form.compose input::placeholder, form.compose textarea::placeholder { color: var(--ink-3); }
|
|
136
|
+
form.compose input:focus, form.compose textarea:focus { outline: none; border-color: var(--accent); }
|
|
137
|
+
form.compose textarea { min-height: 10rem; resize: vertical; }
|
|
138
|
+
.row { display: flex; gap: 0.5rem; justify-content: flex-end; }
|
|
139
|
+
.empty { padding: 4rem 1.5rem; text-align: center; color: var(--ink-3); font: 400 1.125rem/1.5 var(--font-display); font-style: italic; }
|
|
140
|
+
#loadmore { display: block; margin: 0.75rem auto; }
|
|
141
|
+
|
|
142
|
+
/* Mobile: single pane, list <-> conversation */
|
|
143
|
+
@media (max-width: 45rem) {
|
|
144
|
+
main { grid-template-columns: 1fr; }
|
|
145
|
+
#list { border-right: none; }
|
|
146
|
+
main.reading #list { display: none; }
|
|
147
|
+
main:not(.reading) #reader { display: none; }
|
|
148
|
+
#back { display: inline-block; }
|
|
149
|
+
header { padding: 0.625rem 1rem; }
|
|
150
|
+
header .domain { display: none; }
|
|
151
|
+
.thread { padding: 0.75rem 1rem; }
|
|
152
|
+
.convo { padding: 1rem; }
|
|
153
|
+
.bubble .head .preview { max-width: 40vw; }
|
|
154
|
+
}
|
|
37
155
|
</style>
|
|
38
156
|
</head>
|
|
39
157
|
<body>
|
|
40
158
|
<header>
|
|
41
159
|
<h1>{{PROJECT_NAME}} inbox</h1>
|
|
42
|
-
<span
|
|
160
|
+
<span class="domain"></span>
|
|
43
161
|
<span class="spacer"></span>
|
|
44
|
-
<
|
|
45
|
-
|
|
46
|
-
|
|
162
|
+
<div class="actions">
|
|
163
|
+
<button id="compose-btn" class="primary">Compose</button>
|
|
164
|
+
<button id="refresh-btn">Refresh</button>
|
|
165
|
+
<button id="token-btn">Token</button>
|
|
166
|
+
</div>
|
|
47
167
|
</header>
|
|
48
|
-
<main>
|
|
168
|
+
<main id="main">
|
|
49
169
|
<div id="list"><div class="empty">Loading…</div></div>
|
|
50
|
-
<div id="reader"><div class="empty">Select a
|
|
170
|
+
<div id="reader"><div class="empty">Select a conversation</div></div>
|
|
51
171
|
</main>
|
|
52
172
|
|
|
53
173
|
<dialog id="compose">
|
|
174
|
+
<h3 id="compose-title">New message</h3>
|
|
54
175
|
<form class="compose" id="compose-form" method="dialog">
|
|
55
176
|
<input name="to" placeholder="To" required>
|
|
56
|
-
<input name="from" placeholder="From (
|
|
177
|
+
<input name="from" placeholder="From (default inbox)">
|
|
57
178
|
<input name="subject" placeholder="Subject" required>
|
|
58
|
-
<input name="inReplyTo"
|
|
179
|
+
<input name="inReplyTo" type="hidden">
|
|
59
180
|
<textarea name="text" placeholder="Message" required></textarea>
|
|
60
181
|
<div class="row">
|
|
61
182
|
<button type="button" id="compose-cancel">Cancel</button>
|
|
@@ -68,7 +189,7 @@
|
|
|
68
189
|
const $ = (s) => document.querySelector(s)
|
|
69
190
|
let token = localStorage.getItem('inbox_token') || ''
|
|
70
191
|
let cursor = null
|
|
71
|
-
let
|
|
192
|
+
let currentThread = null
|
|
72
193
|
|
|
73
194
|
function askToken(force) {
|
|
74
195
|
if (token && !force) return token
|
|
@@ -88,78 +209,118 @@ async function api(path, opts = {}) {
|
|
|
88
209
|
}
|
|
89
210
|
|
|
90
211
|
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]))
|
|
91
|
-
|
|
212
|
+
function fmtDate(d) {
|
|
213
|
+
const t = new Date(d)
|
|
214
|
+
if (isNaN(t)) return ''
|
|
215
|
+
const sameDay = t.toDateString() === new Date().toDateString()
|
|
216
|
+
return sameDay
|
|
217
|
+
? t.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
|
|
218
|
+
: t.toLocaleDateString([], { month: 'short', day: 'numeric' }) +
|
|
219
|
+
(t.getFullYear() !== new Date().getFullYear() ? ' ' + t.getFullYear() : '')
|
|
220
|
+
}
|
|
92
221
|
|
|
93
222
|
async function loadList(append) {
|
|
94
223
|
askToken(false)
|
|
95
224
|
try {
|
|
96
225
|
const q = append && cursor ? '?cursor=' + encodeURIComponent(cursor) : ''
|
|
97
|
-
const data = await api('/api/
|
|
226
|
+
const data = await api('/api/threads' + q)
|
|
98
227
|
cursor = data.nextCursor
|
|
99
|
-
const html = data.
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
<span class="
|
|
104
|
-
|
|
105
|
-
|
|
228
|
+
const html = data.threads.map((t) => {
|
|
229
|
+
const who = t.direction === 'outbound' ? t.to_addr : t.from_addr
|
|
230
|
+
const badges =
|
|
231
|
+
(t.thread_count > 1 ? `<span class="badge count">${t.thread_count}</span>` : '') +
|
|
232
|
+
(t.direction === 'outbound' ? '<span class="badge sent">sent</span>' : '')
|
|
233
|
+
return `
|
|
234
|
+
<div class="thread" data-thread="${esc(t.thread_id)}">
|
|
235
|
+
<div class="top">
|
|
236
|
+
<span class="who">${esc(who)}</span>
|
|
237
|
+
${badges}
|
|
238
|
+
<span class="when">${esc(fmtDate(t.created_at))}</span>
|
|
239
|
+
</div>
|
|
240
|
+
<span class="subject">${esc(t.subject) || '(no subject)'}</span>
|
|
241
|
+
<span class="snippet">${esc(t.snippet)}</span>
|
|
242
|
+
</div>`
|
|
243
|
+
}).join('')
|
|
106
244
|
const more = cursor ? '<button id="loadmore">Load more</button>' : ''
|
|
107
245
|
if (append) { $('#loadmore')?.remove(); $('#list').insertAdjacentHTML('beforeend', html + more) }
|
|
108
246
|
else $('#list').innerHTML = (html || '<div class="empty">No messages yet</div>') + more
|
|
247
|
+
if (currentThread) highlightActive()
|
|
109
248
|
} catch (e) {
|
|
110
249
|
$('#list').innerHTML = '<div class="empty">' + esc(e.message) + '</div>'
|
|
111
250
|
}
|
|
112
251
|
}
|
|
113
252
|
|
|
114
|
-
|
|
115
|
-
document.querySelectorAll('.
|
|
253
|
+
function highlightActive() {
|
|
254
|
+
document.querySelectorAll('.thread').forEach((el) =>
|
|
255
|
+
el.classList.toggle('active', el.dataset.thread === currentThread))
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function openThread(threadId) {
|
|
259
|
+
currentThread = threadId
|
|
260
|
+
highlightActive()
|
|
261
|
+
$('#main').classList.add('reading')
|
|
116
262
|
$('#reader').innerHTML = '<div class="empty">Loading…</div>'
|
|
117
263
|
try {
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
264
|
+
const { messages } = await api('/api/threads/' + encodeURIComponent(threadId))
|
|
265
|
+
const last = messages[messages.length - 1]
|
|
266
|
+
const bubbles = messages.map((m, i) => {
|
|
267
|
+
const collapsed = messages.length > 1 && i < messages.length - 1
|
|
268
|
+
const out = m.direction === 'outbound'
|
|
269
|
+
return `
|
|
270
|
+
<div class="bubble ${out ? 'outbound' : ''} ${collapsed ? 'collapsed' : ''}" data-id="${esc(m.id)}">
|
|
271
|
+
<div class="head">
|
|
272
|
+
<span class="who">${esc(out ? 'You' : m.from_addr)}</span>
|
|
273
|
+
<span class="arrow">→ ${esc(m.to_addr)}</span>
|
|
274
|
+
${out ? '<span class="badge sent">sent</span>' : ''}
|
|
275
|
+
<span class="preview">${esc(m.snippet)}</span>
|
|
276
|
+
<span class="when">${esc(fmtDate(m.date || m.created_at))}</span>
|
|
277
|
+
</div>
|
|
278
|
+
<div class="body">${m.html_body
|
|
279
|
+
? `<iframe sandbox="" referrerpolicy="no-referrer"></iframe>`
|
|
280
|
+
: `<pre>${esc(m.text_body)}</pre>`}</div>
|
|
281
|
+
<div class="tools">
|
|
282
|
+
${m.r2_key ? `<button class="raw" data-id="${esc(m.id)}">Raw</button>` : ''}
|
|
283
|
+
<button class="del danger" data-id="${esc(m.id)}">Delete</button>
|
|
284
|
+
</div>
|
|
285
|
+
</div>`
|
|
286
|
+
}).join('')
|
|
123
287
|
$('#reader').innerHTML = `
|
|
124
|
-
<div class="
|
|
125
|
-
<
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
<button id="reply-btn">Reply</button>
|
|
129
|
-
<a href="/api/messages/${esc(m.id)}/raw"><button type="button" id="raw-btn">Raw</button></a>
|
|
130
|
-
<button id="delete-btn">Delete</button>
|
|
288
|
+
<div class="convo">
|
|
289
|
+
<div class="convo-head">
|
|
290
|
+
<button id="back">← Back</button>
|
|
291
|
+
<h2>${esc(last.subject) || '(no subject)'}</h2>
|
|
131
292
|
</div>
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
293
|
+
${bubbles}
|
|
294
|
+
<div class="reply-bar">
|
|
295
|
+
<button id="reply-btn" class="primary">Reply</button>
|
|
296
|
+
</div>
|
|
297
|
+
</div>`
|
|
298
|
+
// srcdoc can't be set via innerHTML string safely; bind after render.
|
|
299
|
+
messages.forEach((m) => {
|
|
300
|
+
if (!m.html_body) return
|
|
301
|
+
const frame = document.querySelector(`.bubble[data-id="${CSS.escape(m.id)}"] iframe`)
|
|
302
|
+
if (frame) frame.srcdoc = m.html_body
|
|
139
303
|
})
|
|
140
|
-
$('#
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
if (!confirm('Delete this message?')) return
|
|
149
|
-
await api('/api/messages/' + m.id, { method: 'DELETE' })
|
|
150
|
-
$('#reader').innerHTML = '<div class="empty">Deleted</div>'
|
|
151
|
-
loadList()
|
|
152
|
-
}
|
|
304
|
+
$('#back').onclick = () => { $('#main').classList.remove('reading'); currentThread = null; highlightActive() }
|
|
305
|
+
const replyTo = [...messages].reverse().find((m) => m.direction === 'inbound') || last
|
|
306
|
+
$('#reply-btn').onclick = () => openCompose({
|
|
307
|
+
to: replyTo.direction === 'outbound' ? replyTo.to_addr : replyTo.from_addr,
|
|
308
|
+
from: replyTo.direction === 'outbound' ? replyTo.from_addr : replyTo.to_addr,
|
|
309
|
+
subject: (last.subject || '').match(/^re:/i) ? last.subject : 'Re: ' + (last.subject || ''),
|
|
310
|
+
inReplyTo: last.message_id,
|
|
311
|
+
}, 'Reply')
|
|
153
312
|
} catch (e) {
|
|
154
313
|
$('#reader').innerHTML = '<div class="empty">' + esc(e.message) + '</div>'
|
|
155
314
|
}
|
|
156
315
|
}
|
|
157
316
|
|
|
158
|
-
function openCompose(prefill = {}) {
|
|
317
|
+
function openCompose(prefill = {}, title = 'New message') {
|
|
159
318
|
const f = $('#compose-form')
|
|
160
319
|
f.reset()
|
|
320
|
+
$('#compose-title').textContent = title
|
|
161
321
|
for (const [k, v] of Object.entries(prefill)) if (f[k]) f[k].value = v || ''
|
|
162
322
|
$('#compose').showModal()
|
|
323
|
+
f.text.focus()
|
|
163
324
|
}
|
|
164
325
|
|
|
165
326
|
$('#compose-form').addEventListener('submit', async (e) => {
|
|
@@ -168,8 +329,10 @@ $('#compose-form').addEventListener('submit', async (e) => {
|
|
|
168
329
|
const body = Object.fromEntries(['to', 'from', 'subject', 'inReplyTo', 'text']
|
|
169
330
|
.map((k) => [k, f[k].value.trim()]).filter(([, v]) => v))
|
|
170
331
|
try {
|
|
171
|
-
await api('/api/send', { method: 'POST', body: JSON.stringify(body) })
|
|
332
|
+
const r = await api('/api/send', { method: 'POST', body: JSON.stringify(body) })
|
|
172
333
|
$('#compose').close()
|
|
334
|
+
await loadList()
|
|
335
|
+
if (r.threadId) openThread(r.threadId)
|
|
173
336
|
} catch (err) { alert('Send failed: ' + err.message) }
|
|
174
337
|
})
|
|
175
338
|
|
|
@@ -177,10 +340,37 @@ $('#compose-cancel').onclick = () => $('#compose').close()
|
|
|
177
340
|
$('#compose-btn').onclick = () => openCompose()
|
|
178
341
|
$('#refresh-btn').onclick = () => loadList()
|
|
179
342
|
$('#token-btn').onclick = () => { askToken(true); loadList() }
|
|
343
|
+
|
|
180
344
|
$('#list').addEventListener('click', (e) => {
|
|
181
345
|
if (e.target.id === 'loadmore') return loadList(true)
|
|
182
|
-
const
|
|
183
|
-
if (
|
|
346
|
+
const t = e.target.closest('.thread')
|
|
347
|
+
if (t) openThread(t.dataset.thread)
|
|
348
|
+
})
|
|
349
|
+
|
|
350
|
+
$('#reader').addEventListener('click', async (e) => {
|
|
351
|
+
const head = e.target.closest('.bubble .head')
|
|
352
|
+
if (head && !e.target.closest('button')) {
|
|
353
|
+
head.closest('.bubble').classList.toggle('collapsed')
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
const raw = e.target.closest('button.raw')
|
|
357
|
+
if (raw) {
|
|
358
|
+
const res = await fetch('/api/messages/' + raw.dataset.id + '/raw', { headers: { authorization: 'Bearer ' + token } })
|
|
359
|
+
const blob = await res.blob()
|
|
360
|
+
const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(blob), download: raw.dataset.id + '.eml' })
|
|
361
|
+
a.click()
|
|
362
|
+
return
|
|
363
|
+
}
|
|
364
|
+
const del = e.target.closest('button.del')
|
|
365
|
+
if (del) {
|
|
366
|
+
if (!confirm('Delete this message?')) return
|
|
367
|
+
await api('/api/messages/' + del.dataset.id, { method: 'DELETE' })
|
|
368
|
+
const thread = currentThread
|
|
369
|
+
await loadList()
|
|
370
|
+
const stillThere = document.querySelector(`.thread[data-thread="${CSS.escape(thread)}"]`)
|
|
371
|
+
if (stillThere) openThread(thread)
|
|
372
|
+
else { $('#reader').innerHTML = '<div class="empty">Deleted</div>'; $('#main').classList.remove('reading'); currentThread = null }
|
|
373
|
+
}
|
|
184
374
|
})
|
|
185
375
|
|
|
186
376
|
loadList()
|
|
@@ -5,5 +5,5 @@
|
|
|
5
5
|
"targetDir": "packages/inbox",
|
|
6
6
|
"modules": ["cloudflare-email"],
|
|
7
7
|
"secrets": ["INBOX_TOKEN", "CLOUDFLARE_API_TOKEN"],
|
|
8
|
-
"instructions": "1) Edit packages/inbox/wrangler.jsonc: set DEFAULT_FROM to an address on your email domain (e.g. inbox@mail.example.com).\n2) Create two instance files in packages/infra/environments/<env>/:\n\n // inbox.ts\n import { cloudflareModule } from '../../modules/cloudflare'\n export default cloudflareModule.instance({\n name: 'inbox',\n config: { workdir: 'packages/inbox', accountId: '<account id>', workerSecrets: ['INBOX_TOKEN'] },\n })\n\n // email.ts\n import { cloudflareEmailModule } from '../../modules/cloudflare-email'\n import inbox from './inbox'\n export default cloudflareEmailModule.instance({\n name: 'email',\n imports: [inbox],\n config: {\n accountId: '<account id>', zoneId: '<zone id>', domain: 'mail.<your-domain>',\n enableSending: true, enableRouting: true,\n catchAll: { action: 'worker', workerName: '
|
|
8
|
+
"instructions": "1) Edit packages/inbox/wrangler.jsonc: set DEFAULT_FROM to an address on your email domain (e.g. inbox@mail.example.com).\n2) Create two instance files in packages/infra/environments/<env>/:\n\n // inbox.ts\n import { cloudflareModule } from '../../modules/cloudflare'\n export default cloudflareModule.instance({\n name: 'inbox',\n config: { workdir: 'packages/inbox', accountId: '<account id>', workerSecrets: ['INBOX_TOKEN'] },\n })\n\n // email.ts\n import { cloudflareEmailModule } from '../../modules/cloudflare-email'\n import inbox from './inbox'\n export default cloudflareEmailModule.instance({\n name: 'email',\n imports: [inbox],\n config: {\n accountId: '<account id>', zoneId: '<zone id>', domain: 'mail.<your-domain>',\n enableSending: true, enableRouting: true,\n catchAll: { action: 'worker', workerName: { from: 'inbox', output: 'workerName' } },\n },\n })\n\n3) Add INBOX_TOKEN (any long random string, e.g. `openssl rand -hex 32`) to secrets.yaml, and make sure CLOUDFLARE_API_TOKEN has the scopes the cloudflare-email module documents.\n4) `zbc apply <env>`. Create the R2 bucket if wrangler asks for it (`wrangler r2 bucket create <project>-inbox-raw`).\nNote: Cloudflare holds newly onboarded sending domains in a preview sandbox (verified recipients only) for a short period after DNS validates; arbitrary-recipient sending starts working once it drops."
|
|
9
9
|
}
|
|
@@ -18,10 +18,17 @@ export interface MessageMeta {
|
|
|
18
18
|
snippet: string
|
|
19
19
|
size: number
|
|
20
20
|
created_at: string
|
|
21
|
+
direction: 'inbound' | 'outbound'
|
|
22
|
+
thread_id: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ThreadMeta extends MessageMeta {
|
|
26
|
+
thread_count: number
|
|
21
27
|
}
|
|
22
28
|
|
|
23
29
|
export interface MessageFull extends MessageMeta {
|
|
24
30
|
message_id: string
|
|
31
|
+
in_reply_to: string
|
|
25
32
|
text_body: string
|
|
26
33
|
html_body: string
|
|
27
34
|
r2_key: string
|
|
@@ -41,6 +48,17 @@ export interface InsertMessage {
|
|
|
41
48
|
r2_key: string
|
|
42
49
|
attachments_json: string
|
|
43
50
|
size: number
|
|
51
|
+
direction: 'inbound' | 'outbound'
|
|
52
|
+
in_reply_to: string
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Strip Re:/Fwd: prefixes + whitespace so replies fall into the same thread. */
|
|
56
|
+
function normalizeSubject(subject: string): string {
|
|
57
|
+
return subject
|
|
58
|
+
.replace(/^(\s*(re|fwd?|fw)\s*:\s*)+/i, '')
|
|
59
|
+
.replace(/\s+/g, ' ')
|
|
60
|
+
.trim()
|
|
61
|
+
.toLowerCase()
|
|
44
62
|
}
|
|
45
63
|
|
|
46
64
|
export class Inbox extends DurableObject {
|
|
@@ -67,14 +85,88 @@ export class Inbox extends DurableObject {
|
|
|
67
85
|
);
|
|
68
86
|
CREATE INDEX IF NOT EXISTS idx_messages_created ON messages (created_at DESC, id DESC);
|
|
69
87
|
`)
|
|
88
|
+
// Additive migration for pre-threading deployments (v1 rows had no
|
|
89
|
+
// direction/thread columns). ALTER TABLE has no IF NOT EXISTS.
|
|
90
|
+
const cols = this.sql
|
|
91
|
+
.exec(`SELECT name FROM pragma_table_info('messages')`)
|
|
92
|
+
.toArray() as unknown as Array<{ name: string }>
|
|
93
|
+
const names = new Set(cols.map((c) => c.name))
|
|
94
|
+
if (!names.has('direction')) {
|
|
95
|
+
this.sql.exec(`ALTER TABLE messages ADD COLUMN direction TEXT NOT NULL DEFAULT 'inbound'`)
|
|
96
|
+
}
|
|
97
|
+
if (!names.has('in_reply_to')) {
|
|
98
|
+
this.sql.exec(`ALTER TABLE messages ADD COLUMN in_reply_to TEXT NOT NULL DEFAULT ''`)
|
|
99
|
+
}
|
|
100
|
+
if (!names.has('thread_id')) {
|
|
101
|
+
this.sql.exec(`ALTER TABLE messages ADD COLUMN thread_id TEXT NOT NULL DEFAULT ''`)
|
|
102
|
+
// Backfill: pre-existing rows each become their own thread, and their
|
|
103
|
+
// message_ids get normalized to the bare (bracketless) form the worker
|
|
104
|
+
// now stores.
|
|
105
|
+
this.sql.exec(
|
|
106
|
+
`UPDATE messages SET message_id = replace(replace(trim(message_id), '<', ''), '>', '')`,
|
|
107
|
+
)
|
|
108
|
+
this.sql.exec(`UPDATE messages SET thread_id = id WHERE thread_id = ''`)
|
|
109
|
+
}
|
|
110
|
+
this.sql.exec(`CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages (thread_id, id)`)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Thread resolution, most-reliable first:
|
|
115
|
+
* 1. in_reply_to matches a stored message's RFC Message-ID → that thread.
|
|
116
|
+
* 2. Normalized subject matches an existing thread that shares a
|
|
117
|
+
* participant address (covers providers that rewrite Message-IDs).
|
|
118
|
+
* 3. New thread rooted at this row's id.
|
|
119
|
+
*/
|
|
120
|
+
private resolveThreadId(
|
|
121
|
+
rowId: string,
|
|
122
|
+
inReplyTo: string,
|
|
123
|
+
subject: string,
|
|
124
|
+
fromAddr: string,
|
|
125
|
+
toAddr: string,
|
|
126
|
+
): string {
|
|
127
|
+
if (inReplyTo) {
|
|
128
|
+
const byRef = this.sql
|
|
129
|
+
.exec(`SELECT thread_id FROM messages WHERE message_id = ? LIMIT 1`, inReplyTo)
|
|
130
|
+
.toArray()[0] as unknown as { thread_id: string } | undefined
|
|
131
|
+
if (byRef?.thread_id) return byRef.thread_id
|
|
132
|
+
}
|
|
133
|
+
const norm = normalizeSubject(subject)
|
|
134
|
+
if (norm) {
|
|
135
|
+
const participants = [fromAddr, toAddr].map((a) => a.toLowerCase())
|
|
136
|
+
const rows = this.sql
|
|
137
|
+
.exec(
|
|
138
|
+
`SELECT thread_id, subject, from_addr, to_addr FROM messages ORDER BY id DESC LIMIT 200`,
|
|
139
|
+
)
|
|
140
|
+
.toArray() as unknown as Array<{
|
|
141
|
+
thread_id: string
|
|
142
|
+
subject: string
|
|
143
|
+
from_addr: string
|
|
144
|
+
to_addr: string
|
|
145
|
+
}>
|
|
146
|
+
const match = rows.find(
|
|
147
|
+
(r) =>
|
|
148
|
+
normalizeSubject(r.subject ?? '') === norm &&
|
|
149
|
+
[r.from_addr, r.to_addr].some((a) => participants.includes((a ?? '').toLowerCase())),
|
|
150
|
+
)
|
|
151
|
+
if (match) return match.thread_id
|
|
152
|
+
}
|
|
153
|
+
return rowId
|
|
70
154
|
}
|
|
71
155
|
|
|
72
|
-
insert(msg: InsertMessage):
|
|
156
|
+
insert(msg: InsertMessage): { threadId: string } {
|
|
157
|
+
const threadId = this.resolveThreadId(
|
|
158
|
+
msg.id,
|
|
159
|
+
msg.in_reply_to,
|
|
160
|
+
msg.subject,
|
|
161
|
+
msg.from_addr,
|
|
162
|
+
msg.to_addr,
|
|
163
|
+
)
|
|
73
164
|
this.sql.exec(
|
|
74
165
|
`INSERT INTO messages
|
|
75
166
|
(id, message_id, from_addr, to_addr, subject, date, snippet,
|
|
76
|
-
text_body, html_body, r2_key, attachments_json, size, created_at
|
|
77
|
-
|
|
167
|
+
text_body, html_body, r2_key, attachments_json, size, created_at,
|
|
168
|
+
direction, in_reply_to, thread_id)
|
|
169
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
78
170
|
msg.id,
|
|
79
171
|
msg.message_id,
|
|
80
172
|
msg.from_addr,
|
|
@@ -88,7 +180,11 @@ export class Inbox extends DurableObject {
|
|
|
88
180
|
msg.attachments_json,
|
|
89
181
|
msg.size,
|
|
90
182
|
new Date().toISOString(),
|
|
183
|
+
msg.direction,
|
|
184
|
+
msg.in_reply_to,
|
|
185
|
+
threadId,
|
|
91
186
|
)
|
|
187
|
+
return { threadId }
|
|
92
188
|
}
|
|
93
189
|
|
|
94
190
|
/** Newest-first page. `cursor` is the last-seen id (ids are time-ordered). */
|
|
@@ -97,7 +193,7 @@ export class Inbox extends DurableObject {
|
|
|
97
193
|
const rows = (cursor
|
|
98
194
|
? this.sql
|
|
99
195
|
.exec(
|
|
100
|
-
`SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
|
|
196
|
+
`SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id
|
|
101
197
|
FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?`,
|
|
102
198
|
cursor,
|
|
103
199
|
capped + 1,
|
|
@@ -105,7 +201,7 @@ export class Inbox extends DurableObject {
|
|
|
105
201
|
.toArray()
|
|
106
202
|
: this.sql
|
|
107
203
|
.exec(
|
|
108
|
-
`SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
|
|
204
|
+
`SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id
|
|
109
205
|
FROM messages ORDER BY id DESC LIMIT ?`,
|
|
110
206
|
capped + 1,
|
|
111
207
|
)
|
|
@@ -115,11 +211,53 @@ export class Inbox extends DurableObject {
|
|
|
115
211
|
return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
|
|
116
212
|
}
|
|
117
213
|
|
|
214
|
+
/**
|
|
215
|
+
* Newest-first page of THREADS: the latest message of each thread plus a
|
|
216
|
+
* count. `cursor` is the last-seen latest-message id.
|
|
217
|
+
*/
|
|
218
|
+
listThreads(limit = 50, cursor?: string): { threads: ThreadMeta[]; nextCursor: string | null } {
|
|
219
|
+
const capped = Math.min(Math.max(limit, 1), 200)
|
|
220
|
+
const base = `
|
|
221
|
+
SELECT m.id, m.from_addr, m.to_addr, m.subject, m.date, m.snippet, m.size,
|
|
222
|
+
m.created_at, m.direction, m.thread_id,
|
|
223
|
+
(SELECT COUNT(*) FROM messages c WHERE c.thread_id = m.thread_id) AS thread_count
|
|
224
|
+
FROM messages m
|
|
225
|
+
WHERE m.id = (SELECT MAX(id) FROM messages x WHERE x.thread_id = m.thread_id)`
|
|
226
|
+
const rows = (cursor
|
|
227
|
+
? this.sql
|
|
228
|
+
.exec(`${base} AND m.id < ? ORDER BY m.id DESC LIMIT ?`, cursor, capped + 1)
|
|
229
|
+
.toArray()
|
|
230
|
+
: this.sql
|
|
231
|
+
.exec(`${base} ORDER BY m.id DESC LIMIT ?`, capped + 1)
|
|
232
|
+
.toArray()) as unknown as ThreadMeta[]
|
|
233
|
+
const hasMore = rows.length > capped
|
|
234
|
+
const page = hasMore ? rows.slice(0, capped) : rows
|
|
235
|
+
return { threads: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Every message in a thread, oldest-first, with full bodies. */
|
|
239
|
+
getThread(threadId: string): MessageFull[] {
|
|
240
|
+
const rows = this.sql
|
|
241
|
+
.exec(
|
|
242
|
+
`SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
|
|
243
|
+
text_body, html_body, r2_key, attachments_json, size, created_at,
|
|
244
|
+
direction, in_reply_to, thread_id
|
|
245
|
+
FROM messages WHERE thread_id = ? ORDER BY id ASC`,
|
|
246
|
+
threadId,
|
|
247
|
+
)
|
|
248
|
+
.toArray() as unknown as Array<MessageFull & { attachments_json: string }>
|
|
249
|
+
return rows.map(({ attachments_json, ...rest }) => ({
|
|
250
|
+
...rest,
|
|
251
|
+
attachments: JSON.parse(attachments_json || '[]'),
|
|
252
|
+
}))
|
|
253
|
+
}
|
|
254
|
+
|
|
118
255
|
get(id: string): MessageFull | null {
|
|
119
256
|
const row = this.sql
|
|
120
257
|
.exec(
|
|
121
258
|
`SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
|
|
122
|
-
text_body, html_body, r2_key, attachments_json, size, created_at
|
|
259
|
+
text_body, html_body, r2_key, attachments_json, size, created_at,
|
|
260
|
+
direction, in_reply_to, thread_id
|
|
123
261
|
FROM messages WHERE id = ?`,
|
|
124
262
|
id,
|
|
125
263
|
)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Inbox Worker: an agent-accessible
|
|
2
|
+
* Inbox Worker: an agent-accessible email inbox.
|
|
3
3
|
*
|
|
4
4
|
* - `email()` handler: Email Routing (catch-all) delivers inbound mail here.
|
|
5
5
|
* Raw MIME → R2; parsed metadata + bodies → the Inbox Durable Object.
|
|
@@ -50,6 +50,14 @@ function newId(): string {
|
|
|
50
50
|
return `${time}-${suffix}`
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* Normalize an RFC 5322 Message-ID to its bare form (no angle brackets or
|
|
55
|
+
* whitespace) so stored ids and In-Reply-To references compare equal.
|
|
56
|
+
*/
|
|
57
|
+
function normalizeMsgId(id: string | undefined | null): string {
|
|
58
|
+
return (id ?? '').replace(/[\s<>]/g, '')
|
|
59
|
+
}
|
|
60
|
+
|
|
53
61
|
/** Constant-time bearer check: compare SHA-256 digests so length never leaks. */
|
|
54
62
|
async function authorized(request: Request, env: Env): Promise<boolean> {
|
|
55
63
|
if (!env.INBOX_TOKEN) return false
|
|
@@ -101,7 +109,9 @@ export default {
|
|
|
101
109
|
|
|
102
110
|
await inboxStub(env).insert({
|
|
103
111
|
id,
|
|
104
|
-
|
|
112
|
+
direction: 'inbound',
|
|
113
|
+
in_reply_to: normalizeMsgId(parsed.inReplyTo),
|
|
114
|
+
message_id: normalizeMsgId(parsed.messageId),
|
|
105
115
|
// Prefer the header From (what the sender shows as) over the SMTP
|
|
106
116
|
// envelope sender (often a bounce address like bounces@cf-bounce.…).
|
|
107
117
|
from_addr: parsed.from?.address ?? message.from,
|
|
@@ -144,6 +154,20 @@ export default {
|
|
|
144
154
|
return json(await stub.list(Number.isFinite(limit) ? limit : 50, cursor))
|
|
145
155
|
}
|
|
146
156
|
|
|
157
|
+
// GET /api/threads?limit=&cursor= — newest-first, one row per thread
|
|
158
|
+
if (pathname === '/api/threads' && request.method === 'GET') {
|
|
159
|
+
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
160
|
+
const cursor = url.searchParams.get('cursor') ?? undefined
|
|
161
|
+
return json(await stub.listThreads(Number.isFinite(limit) ? limit : 50, cursor))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// GET /api/threads/:id — all messages in the thread, oldest-first
|
|
165
|
+
const threadMatch = pathname.match(/^\/api\/threads\/([^/]+)$/)
|
|
166
|
+
if (threadMatch && request.method === 'GET') {
|
|
167
|
+
const messages = await stub.getThread(threadMatch[1]!)
|
|
168
|
+
return messages.length ? json({ messages }) : json({ error: 'not found' }, 404)
|
|
169
|
+
}
|
|
170
|
+
|
|
147
171
|
// POST /api/send
|
|
148
172
|
if (pathname === '/api/send' && request.method === 'POST') {
|
|
149
173
|
let body: SendBody
|
|
@@ -158,8 +182,15 @@ export default {
|
|
|
158
182
|
const from = body.from ?? env.DEFAULT_FROM
|
|
159
183
|
if (!from) return json({ error: 'no from address (set DEFAULT_FROM or pass from)' }, 400)
|
|
160
184
|
|
|
161
|
-
|
|
162
|
-
|
|
185
|
+
// Email Sending only accepts whitelisted custom headers (a Message-ID
|
|
186
|
+
// of our own is rejected), so the wire Message-ID is provider-chosen
|
|
187
|
+
// and unknown to us. We store a synthetic one for OUR send chain;
|
|
188
|
+
// recipient replies thread via the subject+participant fallback.
|
|
189
|
+
const id = newId()
|
|
190
|
+
const messageId = `${id}@${from.split('@')[1] ?? 'localhost'}`
|
|
191
|
+
const inReplyTo = normalizeMsgId(body.inReplyTo)
|
|
192
|
+
const headers: Record<string, string> | undefined = inReplyTo
|
|
193
|
+
? { 'In-Reply-To': `<${inReplyTo}>`, References: `<${inReplyTo}>` }
|
|
163
194
|
: undefined
|
|
164
195
|
|
|
165
196
|
try {
|
|
@@ -174,7 +205,32 @@ export default {
|
|
|
174
205
|
} catch (err) {
|
|
175
206
|
return json({ error: `send failed: ${(err as Error).message}` }, 502)
|
|
176
207
|
}
|
|
177
|
-
|
|
208
|
+
|
|
209
|
+
// Record the outbound message so the inbox shows both sides of a
|
|
210
|
+
// conversation. No raw MIME (we never see the provider's final wire
|
|
211
|
+
// form), so r2_key stays empty and /raw 404s for these.
|
|
212
|
+
const text = body.text ?? ''
|
|
213
|
+
const snippet = (text || (body.html ?? '').replace(/<[^>]+>/g, ' '))
|
|
214
|
+
.replace(/\s+/g, ' ')
|
|
215
|
+
.trim()
|
|
216
|
+
.slice(0, 200)
|
|
217
|
+
const { threadId } = await stub.insert({
|
|
218
|
+
id,
|
|
219
|
+
direction: 'outbound',
|
|
220
|
+
in_reply_to: inReplyTo,
|
|
221
|
+
message_id: messageId,
|
|
222
|
+
from_addr: from,
|
|
223
|
+
to_addr: body.to,
|
|
224
|
+
subject: body.subject,
|
|
225
|
+
date: new Date().toISOString(),
|
|
226
|
+
snippet,
|
|
227
|
+
text_body: text,
|
|
228
|
+
html_body: body.html ?? '',
|
|
229
|
+
r2_key: '',
|
|
230
|
+
attachments_json: '[]',
|
|
231
|
+
size: text.length + (body.html?.length ?? 0),
|
|
232
|
+
})
|
|
233
|
+
return json({ ok: true, id, from, to: body.to, messageId, threadId })
|
|
178
234
|
}
|
|
179
235
|
|
|
180
236
|
// /api/messages/:id[/raw]
|
|
@@ -185,6 +241,7 @@ export default {
|
|
|
185
241
|
if (rawSuffix && request.method === 'GET') {
|
|
186
242
|
const msg = await stub.get(id!)
|
|
187
243
|
if (!msg) return json({ error: 'not found' }, 404)
|
|
244
|
+
if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
|
|
188
245
|
const obj = await env.RAW.get(msg.r2_key)
|
|
189
246
|
if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
|
|
190
247
|
return new Response(obj.body, {
|
|
@@ -193,6 +193,13 @@ export const cloudflareModule = defineModule({
|
|
|
193
193
|
}),
|
|
194
194
|
outputs: z.object({
|
|
195
195
|
deployUrl: z.string(),
|
|
196
|
+
/**
|
|
197
|
+
* The deployed Worker's script name, parsed from wrangler's "Deployed
|
|
198
|
+
* <name> triggers" confirmation. Lets dependents reference this worker
|
|
199
|
+
* without repeating the name from wrangler.jsonc (e.g. cloudflare-email's
|
|
200
|
+
* catchAll.workerName as `{ from, output: 'workerName' }`).
|
|
201
|
+
*/
|
|
202
|
+
workerName: z.string(),
|
|
196
203
|
}),
|
|
197
204
|
async apply(config, ctx) {
|
|
198
205
|
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
@@ -243,12 +250,15 @@ export const cloudflareModule = defineModule({
|
|
|
243
250
|
)
|
|
244
251
|
const out = wrangler(workdir, deployArgs, env)
|
|
245
252
|
// Success theater guard: wrangler can exit 0 without actually deploying
|
|
246
|
-
// (the --bun incident above). Require the deploy confirmation line
|
|
247
|
-
|
|
253
|
+
// (the --bun incident above). Require the deploy confirmation line — and
|
|
254
|
+
// capture the deployed script name from it for the workerName output.
|
|
255
|
+
const deployedMatch = out.match(/Deployed\s+(\S+)\s+triggers/)
|
|
256
|
+
if (!deployedMatch) {
|
|
248
257
|
throw new Error(
|
|
249
258
|
`wrangler deploy exited 0 but printed no "Deployed ... triggers" confirmation:\n${out}`,
|
|
250
259
|
)
|
|
251
260
|
}
|
|
261
|
+
const workerName = deployedMatch[1]!
|
|
252
262
|
const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
|
|
253
263
|
const deployUrl = urlMatch?.[0] ?? ''
|
|
254
264
|
console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
|
|
@@ -265,7 +275,7 @@ export const cloudflareModule = defineModule({
|
|
|
265
275
|
console.log(` Set Worker secret: ${name}`)
|
|
266
276
|
}
|
|
267
277
|
|
|
268
|
-
return { deployUrl }
|
|
278
|
+
return { deployUrl, workerName }
|
|
269
279
|
},
|
|
270
280
|
async destroy(config, ctx) {
|
|
271
281
|
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
@@ -98,6 +98,47 @@ async function cfFetch<T>(
|
|
|
98
98
|
return envelope.result
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
/**
|
|
102
|
+
* A worker name: either a literal script name, or a `{ from, output }`
|
|
103
|
+
* reference into an imported instance's outputs (e.g. the cloudflare module
|
|
104
|
+
* emits `workerName`). References make the coupling refactor-safe — a rename
|
|
105
|
+
* in wrangler.jsonc flows through automatically, and a typo'd instance or
|
|
106
|
+
* output is a hard error at apply time instead of a dangling routing rule.
|
|
107
|
+
*/
|
|
108
|
+
const workerRefSchema = z.union([
|
|
109
|
+
z.string(),
|
|
110
|
+
z.object({
|
|
111
|
+
/** Instance name — must be listed in this instance's `imports`. */
|
|
112
|
+
from: z.string(),
|
|
113
|
+
/** Which output of that instance holds the worker name. */
|
|
114
|
+
output: z.string(),
|
|
115
|
+
}),
|
|
116
|
+
])
|
|
117
|
+
|
|
118
|
+
type WorkerRef = z.infer<typeof workerRefSchema>
|
|
119
|
+
|
|
120
|
+
/** Resolve a worker-name entry to its literal string. */
|
|
121
|
+
function resolveWorkerName(
|
|
122
|
+
ref: WorkerRef,
|
|
123
|
+
imports: Record<string, unknown>,
|
|
124
|
+
fieldName: string,
|
|
125
|
+
): string {
|
|
126
|
+
if (typeof ref === 'string') return ref
|
|
127
|
+
const instanceOutputs = imports[ref.from]
|
|
128
|
+
if (instanceOutputs === undefined) {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`${fieldName} references instance "${ref.from}", which is not in this instance's imports`,
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
const value = (instanceOutputs as Record<string, unknown> | null)?.[ref.output]
|
|
134
|
+
if (typeof value !== 'string') {
|
|
135
|
+
throw new Error(
|
|
136
|
+
`${fieldName} references output "${ref.output}" on instance "${ref.from}", which doesn't emit it`,
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
return value
|
|
140
|
+
}
|
|
141
|
+
|
|
101
142
|
/** A routing rule action target. */
|
|
102
143
|
const addressSchema = z.object({
|
|
103
144
|
/** Local part only — the domain comes from config.domain. */
|
|
@@ -105,13 +146,14 @@ const addressSchema = z.object({
|
|
|
105
146
|
action: z.enum(['forward', 'worker']),
|
|
106
147
|
/** forward: a verified destination address (email). */
|
|
107
148
|
destination: z.string().optional(),
|
|
108
|
-
/** worker: the
|
|
109
|
-
workerName:
|
|
149
|
+
/** worker: the script name, literal or `{ from, output }` import reference. */
|
|
150
|
+
workerName: workerRefSchema.optional(),
|
|
110
151
|
})
|
|
111
152
|
|
|
112
153
|
const catchAllSchema = z.object({
|
|
113
154
|
action: z.enum(['worker', 'forward', 'drop']),
|
|
114
|
-
|
|
155
|
+
/** worker: the script name, literal or `{ from, output }` import reference. */
|
|
156
|
+
workerName: workerRefSchema.optional(),
|
|
115
157
|
destination: z.string().optional(),
|
|
116
158
|
})
|
|
117
159
|
|
|
@@ -132,17 +174,18 @@ interface SendingSubdomain {
|
|
|
132
174
|
/** Managed-rule marker so destroy only removes rules this module created. */
|
|
133
175
|
const RULE_PREFIX = 'zbc:'
|
|
134
176
|
|
|
135
|
-
function ruleAction(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
177
|
+
function ruleAction(
|
|
178
|
+
entry: { action: string; destination?: string; workerName?: WorkerRef },
|
|
179
|
+
imports: Record<string, unknown>,
|
|
180
|
+
fieldName: string,
|
|
181
|
+
): { type: string; value?: string[] } {
|
|
139
182
|
if (entry.action === 'forward') {
|
|
140
|
-
if (!entry.destination) throw new Error(
|
|
183
|
+
if (!entry.destination) throw new Error(`${fieldName}: action "forward" requires a destination`)
|
|
141
184
|
return { type: 'forward', value: [entry.destination] }
|
|
142
185
|
}
|
|
143
186
|
if (entry.action === 'worker') {
|
|
144
|
-
if (!entry.workerName) throw new Error(
|
|
145
|
-
return { type: 'worker', value: [entry.workerName] }
|
|
187
|
+
if (!entry.workerName) throw new Error(`${fieldName}: action "worker" requires a workerName`)
|
|
188
|
+
return { type: 'worker', value: [resolveWorkerName(entry.workerName, imports, fieldName)] }
|
|
146
189
|
}
|
|
147
190
|
return { type: 'drop' }
|
|
148
191
|
}
|
|
@@ -343,7 +386,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
343
386
|
name: ruleName,
|
|
344
387
|
enabled: true,
|
|
345
388
|
matchers: [{ type: 'literal', field: 'to', value: email }],
|
|
346
|
-
actions: [ruleAction(entry)],
|
|
389
|
+
actions: [ruleAction(entry, ctx.imports, `addresses[${entry.localPart}]`)],
|
|
347
390
|
}
|
|
348
391
|
const existing = existingRules.find(
|
|
349
392
|
(r) =>
|
|
@@ -370,7 +413,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
370
413
|
name: `${RULE_PREFIX}catch-all`,
|
|
371
414
|
enabled: true,
|
|
372
415
|
matchers: [{ type: 'all' }],
|
|
373
|
-
actions: [ruleAction(config.catchAll)],
|
|
416
|
+
actions: [ruleAction(config.catchAll, ctx.imports, 'catchAll')],
|
|
374
417
|
},
|
|
375
418
|
})
|
|
376
419
|
console.log(` Routing: catch-all → ${config.catchAll.action}`)
|