@zabaca/zbc 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/list.ts +6 -3
  5. package/src/commands/update.ts +42 -0
  6. package/src/engine/destroy.ts +23 -2
  7. package/src/engine/resolve.ts +5 -0
  8. package/src/utils/subtree.ts +37 -7
  9. package/src/utils/vendor-stamp.ts +92 -1
  10. package/src/utils/vendored-app.ts +353 -0
  11. package/templates/CLAUDE.md +1 -1
  12. package/templates/apps/walgit/worker/mcp.ts +1 -2
  13. package/templates/apps/warehouse/worker/router.ts +1 -2
  14. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  15. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  16. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  17. package/templates/infra/modules/d1/index.ts +133 -4
  18. package/templates/infra/modules/d1/registry.json +4 -1
  19. package/templates/infra/modules/queue/index.ts +313 -0
  20. package/templates/infra/modules/queue/registry.json +13 -0
  21. package/templates/infra/modules/r2/registry.json +1 -1
  22. package/templates/infra/src/define-module.ts +19 -2
  23. package/templates/infra/src/types.ts +24 -0
  24. package/templates/apps/inbox/package.json +0 -26
  25. package/templates/apps/inbox/public/index.html +0 -379
  26. package/templates/apps/inbox/registry.json +0 -9
  27. package/templates/apps/inbox/tsconfig.json +0 -19
  28. package/templates/apps/inbox/worker/api.ts +0 -197
  29. package/templates/apps/inbox/worker/commands.ts +0 -299
  30. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  31. package/templates/apps/inbox/worker/index.ts +0 -195
  32. package/templates/apps/inbox/worker/mcp.ts +0 -228
  33. package/templates/apps/inbox/worker/shared.ts +0 -117
  34. package/templates/apps/inbox/wrangler.jsonc +0 -48
@@ -1,379 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>Inbox</title>
7
- <style>
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
-
30
- * { box-sizing: border-box; }
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); }
62
- header .spacer { flex: 1; }
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
- }
155
- </style>
156
- </head>
157
- <body>
158
- <header>
159
- <h1>Inbox</h1>
160
- <span class="domain"></span>
161
- <span class="spacer"></span>
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>
167
- </header>
168
- <main id="main">
169
- <div id="list"><div class="empty">Loading…</div></div>
170
- <div id="reader"><div class="empty">Select a conversation</div></div>
171
- </main>
172
-
173
- <dialog id="compose">
174
- <h3 id="compose-title">New message</h3>
175
- <form class="compose" id="compose-form" method="dialog">
176
- <input name="to" placeholder="To" required>
177
- <input name="from" placeholder="From (optional, defaults to DEFAULT_FROM)">
178
- <input name="subject" placeholder="Subject" required>
179
- <input name="inReplyTo" type="hidden">
180
- <textarea name="text" placeholder="Message" required></textarea>
181
- <div class="row">
182
- <button type="button" id="compose-cancel">Cancel</button>
183
- <button type="submit" class="primary">Send</button>
184
- </div>
185
- </form>
186
- </dialog>
187
-
188
- <script>
189
- const $ = (s) => document.querySelector(s)
190
- let token = localStorage.getItem('inbox_token') || ''
191
- let cursor = null
192
- let currentThread = null
193
-
194
- function askToken(force) {
195
- if (token && !force) return token
196
- const t = prompt('Inbox API token (stored in localStorage):', token)
197
- if (t !== null) { token = t.trim(); localStorage.setItem('inbox_token', token) }
198
- return token
199
- }
200
-
201
- async function api(path, opts = {}) {
202
- const res = await fetch(path, {
203
- ...opts,
204
- headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json', ...(opts.headers || {}) },
205
- })
206
- if (res.status === 401) { askToken(true); throw new Error('unauthorized — token updated, retry') }
207
- if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || res.statusText)
208
- return res.json()
209
- }
210
-
211
- const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]))
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
- }
221
-
222
- async function loadList(append) {
223
- askToken(false)
224
- try {
225
- const q = append && cursor ? '?cursor=' + encodeURIComponent(cursor) : ''
226
- const data = await api('/api/threads' + q)
227
- cursor = data.nextCursor
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('')
244
- const more = cursor ? '<button id="loadmore">Load more</button>' : ''
245
- if (append) { $('#loadmore')?.remove(); $('#list').insertAdjacentHTML('beforeend', html + more) }
246
- else $('#list').innerHTML = (html || '<div class="empty">No messages yet</div>') + more
247
- if (currentThread) highlightActive()
248
- } catch (e) {
249
- $('#list').innerHTML = '<div class="empty">' + esc(e.message) + '</div>'
250
- }
251
- }
252
-
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')
262
- $('#reader').innerHTML = '<div class="empty">Loading…</div>'
263
- try {
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('')
287
- $('#reader').innerHTML = `
288
- <div class="convo">
289
- <div class="convo-head">
290
- <button id="back">← Back</button>
291
- <h2>${esc(last.subject) || '(no subject)'}</h2>
292
- </div>
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
303
- })
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')
312
- } catch (e) {
313
- $('#reader').innerHTML = '<div class="empty">' + esc(e.message) + '</div>'
314
- }
315
- }
316
-
317
- function openCompose(prefill = {}, title = 'New message') {
318
- const f = $('#compose-form')
319
- f.reset()
320
- $('#compose-title').textContent = title
321
- for (const [k, v] of Object.entries(prefill)) if (f[k]) f[k].value = v || ''
322
- $('#compose').showModal()
323
- f.text.focus()
324
- }
325
-
326
- $('#compose-form').addEventListener('submit', async (e) => {
327
- e.preventDefault()
328
- const f = e.target
329
- const body = Object.fromEntries(['to', 'from', 'subject', 'inReplyTo', 'text']
330
- .map((k) => [k, f[k].value.trim()]).filter(([, v]) => v))
331
- try {
332
- const r = await api('/api/send', { method: 'POST', body: JSON.stringify(body) })
333
- $('#compose').close()
334
- await loadList()
335
- if (r.threadId) openThread(r.threadId)
336
- } catch (err) { alert('Send failed: ' + err.message) }
337
- })
338
-
339
- $('#compose-cancel').onclick = () => $('#compose').close()
340
- $('#compose-btn').onclick = () => openCompose()
341
- $('#refresh-btn').onclick = () => loadList()
342
- $('#token-btn').onclick = () => { askToken(true); loadList() }
343
-
344
- $('#list').addEventListener('click', (e) => {
345
- if (e.target.id === 'loadmore') return loadList(true)
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
- }
374
- })
375
-
376
- loadList()
377
- </script>
378
- </body>
379
- </html>
@@ -1,9 +0,0 @@
1
- {
2
- "name": "inbox",
3
- "kind": "app",
4
- "description": "Agent-accessible email inbox: a Cloudflare Worker that receives routed mail (SQLite DO metadata + R2 raw MIME), sends via Email Sending, and exposes a bearer-authed JSON API, an MCP server at /mcp (same token), and a minimal web UI",
5
- "targetDir": "packages/inbox",
6
- "modules": ["cloudflare", "cloudflare-email", "r2"],
7
- "secrets": ["INBOX_TOKEN", "CLOUDFLARE_API_TOKEN"],
8
- "instructions": "The scaffolded package is generic — all per-project identity (worker name, R2 bucket, default From address) lives in the instance files, not in wrangler.jsonc.\n\nCreate three instance files in packages/infra/environments/<env>/:\n\n // inbox-raw.ts — the R2 bucket for raw MIME\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: '<project>-inbox-raw' },\n })\n\n // inbox.ts — the worker\n import { cloudflareModule } from '../../modules/cloudflare'\n import inboxRaw from './inbox-raw'\n export default cloudflareModule.instance({\n name: 'inbox',\n imports: [inboxRaw],\n config: {\n workdir: 'packages/inbox',\n accountId: '<account id>',\n workerName: '<project>-inbox',\n workerSecrets: ['INBOX_TOKEN'],\n workerVars: [{ name: 'DEFAULT_FROM', value: 'inbox@mail.<your-domain>' }],\n r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }],\n },\n })\n\n // email.ts — sending + routing for the domain\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\nAdd INBOX_TOKEN (any long random string, e.g. `openssl rand -hex 32`) to secrets.yaml. CLOUDFLARE_API_TOKEN needs the scopes the cloudflare-email module documents PLUS Account → Workers R2 Storage: Edit (for the r2 module).\n\n`zbc apply <env>` provisions the bucket, deploys the worker, and onboards the domain.\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
- }
@@ -1,19 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "esnext",
4
- "module": "esnext",
5
- "moduleResolution": "bundler",
6
- "strict": true,
7
- "esModuleInterop": true,
8
- "skipLibCheck": true,
9
- "forceConsistentCasingInFileNames": true,
10
- "resolveJsonModule": true,
11
- "noUncheckedIndexedAccess": true,
12
- "noEmit": true,
13
- "lib": ["esnext"],
14
- "types": ["@cloudflare/workers-types"]
15
- },
16
- "include": ["worker"],
17
- "// exclude": "Test files are excluded because bun:test's `expect` typings clash with @cloudflare/workers-types' Request/Response shapes when both are in one program (same split warehouse's tsconfig.worker.json documents). `bun test` still type-strips and runs them.",
18
- "exclude": ["node_modules", "**/*.test.ts"]
19
- }
@@ -1,197 +0,0 @@
1
- /**
2
- * The JSON adapter: bearer-authed `/api/*` over the Inbox. One of the two
3
- * adapters (the other is `mcp.ts`) — it parses HTTP, calls a command or a
4
- * read, and renders the result. No mutation logic lives here.
5
- *
6
- * It is a module rather than a block inside `index.ts` for the same reason
7
- * `handleMcp` is: `index.ts` is the Workers entry and imports the Inbox
8
- * Durable Object, which imports `cloudflare:workers` — a specifier bun cannot
9
- * resolve, so a test can never load it. Everything here reaches the DO through
10
- * the `InboxStore` interface, so `worker/commands.test.ts` can drive both
11
- * adapters against the same in-memory fake.
12
- */
13
- import PostalMime from 'postal-mime'
14
- import * as commands from './commands'
15
- import type { DraftBody, SendBody, SendEnv } from './commands'
16
- import type { InboxStore } from './inbox-do'
17
-
18
- export interface ApiEnv extends SendEnv {
19
- RAW: R2Bucket
20
- }
21
-
22
- export interface ApiDeps {
23
- env: ApiEnv
24
- store: InboxStore
25
- }
26
-
27
- export function json(data: unknown, status = 200): Response {
28
- return Response.json(data, { status, headers: { 'cache-control': 'no-store' } })
29
- }
30
-
31
- export async function handleApi(request: Request, deps: ApiDeps): Promise<Response> {
32
- const { env, store } = deps
33
- const url = new URL(request.url)
34
- const { pathname } = url
35
-
36
- // GET /api/messages?limit=&cursor=&label=
37
- if (pathname === '/api/messages' && request.method === 'GET') {
38
- const limit = Number(url.searchParams.get('limit') ?? '50')
39
- const cursor = url.searchParams.get('cursor') ?? undefined
40
- const label = url.searchParams.get('label') ?? undefined
41
- return json(await store.list(Number.isFinite(limit) ? limit : 50, cursor, label))
42
- }
43
-
44
- // GET /api/search?q=&limit= — keyword match over subject + text body
45
- if (pathname === '/api/search' && request.method === 'GET') {
46
- const q = url.searchParams.get('q') ?? ''
47
- if (!q.trim()) return json({ error: 'required: q' }, 400)
48
- const limit = Number(url.searchParams.get('limit') ?? '50')
49
- return json({ messages: await store.search(q.trim(), Number.isFinite(limit) ? limit : 50) })
50
- }
51
-
52
- // GET /api/threads?limit=&cursor= — newest-first, one row per thread
53
- if (pathname === '/api/threads' && request.method === 'GET') {
54
- const limit = Number(url.searchParams.get('limit') ?? '50')
55
- const cursor = url.searchParams.get('cursor') ?? undefined
56
- return json(await store.listThreads(Number.isFinite(limit) ? limit : 50, cursor))
57
- }
58
-
59
- // GET /api/threads/:id — all messages in the thread, oldest-first
60
- const threadMatch = pathname.match(/^\/api\/threads\/([^/]+)$/)
61
- if (threadMatch && request.method === 'GET') {
62
- const messages = await store.getThread(threadMatch[1]!)
63
- return messages.length ? json({ messages }) : json({ error: 'not found' }, 404)
64
- }
65
-
66
- // POST /api/send — immediate, or queued for the DO alarm when sendAt set
67
- if (pathname === '/api/send' && request.method === 'POST') {
68
- let body: SendBody
69
- try {
70
- body = (await request.json()) as SendBody
71
- } catch {
72
- return json({ error: 'invalid JSON body' }, 400)
73
- }
74
- const outcome = await commands.send(env, store, body)
75
- return json(outcome.body, outcome.status)
76
- }
77
-
78
- // GET /api/scheduled — pending + failed scheduled sends, soonest first
79
- if (pathname === '/api/scheduled' && request.method === 'GET') {
80
- const limit = Number(url.searchParams.get('limit') ?? '50')
81
- return json({ scheduled: await store.listScheduled(Number.isFinite(limit) ? limit : 50) })
82
- }
83
-
84
- // DELETE /api/scheduled/:id — cancel a pending (or dismiss a failed) send
85
- const schedMatch = pathname.match(/^\/api\/scheduled\/([^/]+)$/)
86
- if (schedMatch && request.method === 'DELETE') {
87
- const outcome = await commands.cancelScheduled(store, schedMatch[1]!)
88
- return json(outcome.body, outcome.status)
89
- }
90
-
91
- // POST /api/drafts — store an outbound message without sending it
92
- if (pathname === '/api/drafts' && request.method === 'POST') {
93
- let body: DraftBody
94
- try {
95
- body = (await request.json()) as DraftBody
96
- } catch {
97
- return json({ error: 'invalid JSON body' }, 400)
98
- }
99
- const outcome = await commands.createDraft(env, store, body)
100
- return json(outcome.body, outcome.status)
101
- }
102
-
103
- // GET /api/drafts
104
- if (pathname === '/api/drafts' && request.method === 'GET') {
105
- const limit = Number(url.searchParams.get('limit') ?? '50')
106
- return json({ drafts: await store.listDrafts(Number.isFinite(limit) ? limit : 50) })
107
- }
108
-
109
- // PUT /api/drafts/:id | POST /api/drafts/:id/send
110
- const draftMatch = pathname.match(/^\/api\/drafts\/([^/]+)(\/send)?$/)
111
- if (draftMatch) {
112
- const [, draftId, sendSuffix] = draftMatch
113
-
114
- if (!sendSuffix && request.method === 'PUT') {
115
- let body: DraftBody
116
- try {
117
- body = (await request.json()) as DraftBody
118
- } catch {
119
- return json({ error: 'invalid JSON body' }, 400)
120
- }
121
- const outcome = await commands.updateDraft(store, draftId!, body)
122
- return json(outcome.body, outcome.status)
123
- }
124
-
125
- if (sendSuffix && request.method === 'POST') {
126
- const outcome = await commands.sendDraft(env, store, draftId!)
127
- return json(outcome.body, outcome.status)
128
- }
129
- if (!sendSuffix && request.method === 'GET') {
130
- const draft = await store.get(draftId!)
131
- return draft && draft.status === 'draft' ? json(draft) : json({ error: 'not a draft' }, 404)
132
- }
133
- // Deliberately NOT commands.deleteMessage: this route deletes drafts and
134
- // only drafts, refusing anything else, where the command deletes a row of
135
- // any status. Two different operations that happen to share a verb.
136
- if (!sendSuffix && request.method === 'DELETE') {
137
- const draft = await store.get(draftId!)
138
- if (!draft || draft.status !== 'draft') return json({ error: 'not a draft' }, 404)
139
- await store.delete(draftId!)
140
- return json({ ok: true })
141
- }
142
- }
143
-
144
- // GET /api/messages/:id/attachments/:n — raw bytes of one attachment.
145
- // Re-parses the R2 MIME blob per request (cheap at the 5 MiB cap) rather
146
- // than pre-splitting attachments at write time.
147
- const attMatch = pathname.match(/^\/api\/messages\/([^/]+)\/attachments\/(\d+)$/)
148
- if (attMatch && request.method === 'GET') {
149
- const msg = await store.get(attMatch[1]!)
150
- if (!msg) return json({ error: 'not found' }, 404)
151
- if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
152
- const obj = await env.RAW.get(msg.r2_key)
153
- if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
154
- const parsed = await PostalMime.parse(await obj.arrayBuffer())
155
- const n = Number(attMatch[2])
156
- const att = (parsed.attachments ?? [])[n]
157
- if (!att) return json({ error: `no attachment at index ${n}` }, 404)
158
- const body =
159
- typeof att.content === 'string' ? new TextEncoder().encode(att.content) : att.content
160
- return new Response(body, {
161
- headers: {
162
- 'content-type': att.mimeType || 'application/octet-stream',
163
- 'content-disposition': `attachment; filename="${(att.filename ?? 'attachment').replace(/["\r\n]/g, '')}"`,
164
- 'cache-control': 'no-store',
165
- },
166
- })
167
- }
168
-
169
- // /api/messages/:id[/raw]
170
- const match = pathname.match(/^\/api\/messages\/([^/]+)(\/raw)?$/)
171
- if (match) {
172
- const [, id, rawSuffix] = match
173
-
174
- if (rawSuffix && request.method === 'GET') {
175
- const msg = await store.get(id!)
176
- if (!msg) return json({ error: 'not found' }, 404)
177
- if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
178
- const obj = await env.RAW.get(msg.r2_key)
179
- if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
180
- return new Response(obj.body, {
181
- headers: { 'content-type': 'message/rfc822', 'cache-control': 'no-store' },
182
- })
183
- }
184
-
185
- if (!rawSuffix && request.method === 'GET') {
186
- const msg = await store.get(id!)
187
- return msg ? json(msg) : json({ error: 'not found' }, 404)
188
- }
189
-
190
- if (!rawSuffix && request.method === 'DELETE') {
191
- const outcome = await commands.deleteMessage(env, store, id!)
192
- return json(outcome.body, outcome.status)
193
- }
194
- }
195
-
196
- return json({ error: 'not found' }, 404)
197
- }