@zabaca/zbc 0.13.0 → 0.15.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 (48) hide show
  1. package/CHANGELOG.md +117 -6
  2. package/package.json +5 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/apply.ts +33 -9
  5. package/src/commands/destroy.ts +1 -1
  6. package/src/commands/init.ts +1 -0
  7. package/src/engine/apply.ts +110 -22
  8. package/src/engine/destroy.ts +183 -14
  9. package/src/engine/discover.ts +1 -1
  10. package/src/engine/resolve.ts +113 -14
  11. package/src/utils/copy-template.ts +10 -0
  12. package/templates/CLAUDE.md +1 -1
  13. package/templates/apps/inbox/package.json +3 -1
  14. package/templates/apps/inbox/tsconfig.json +3 -1
  15. package/templates/apps/inbox/worker/api.ts +197 -0
  16. package/templates/apps/inbox/worker/commands.ts +299 -0
  17. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  18. package/templates/apps/inbox/worker/index.ts +15 -202
  19. package/templates/apps/inbox/worker/mcp.ts +49 -100
  20. package/templates/infra/modules/cloudflare/index.ts +29 -73
  21. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  22. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  23. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  24. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  25. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  26. package/templates/infra/modules/cloudflare-token/index.ts +10 -32
  27. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  28. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  29. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  30. package/templates/infra/modules/fly/index.ts +17 -42
  31. package/templates/infra/modules/fly/registry.json +1 -1
  32. package/templates/infra/modules/host-file/index.ts +6 -7
  33. package/templates/infra/modules/provision-core/index.ts +21 -15
  34. package/templates/infra/modules/r2/index.ts +40 -71
  35. package/templates/infra/modules/r2/registry.json +1 -1
  36. package/templates/infra/modules/remote-provision/index.ts +1 -3
  37. package/templates/infra/modules/turso/index.ts +2 -15
  38. package/templates/infra/modules/vm-provision/index.ts +10 -3
  39. package/templates/infra/src/context.ts +115 -0
  40. package/templates/infra/src/define-module.ts +41 -2
  41. package/templates/infra/src/index.ts +11 -1
  42. package/templates/infra/src/types.ts +85 -3
  43. package/src/commands/add-registry.test.ts +0 -92
  44. package/src/commands/secret.test.ts +0 -717
  45. package/src/commands/vendor-mode.test.ts +0 -183
  46. package/src/infra-types.ts +0 -38
  47. package/src/utils/subtree.test.ts +0 -127
  48. package/templates/apps/inbox/worker/send-op.ts +0 -174
@@ -0,0 +1,299 @@
1
+ import type { DraftFields, InboxStore } from './inbox-do'
2
+ import { type MailEnv, emitWebhook, makeSnippet, newId, normalizeMsgId, sendMail } from './shared'
3
+
4
+ /**
5
+ * Every mutation the inbox supports, once. The two adapters — `api.ts` (the
6
+ * JSON routes) and `mcp.ts` (the MCP tools) — parse their own input shape,
7
+ * call one of these, and render the `Outcome`; neither holds mutation logic
8
+ * of its own. A Worker cannot fetch its own routes, so this is a module of
9
+ * functions rather than one adapter calling the other.
10
+ *
11
+ * The shape is uniform: `(env?, store, input) -> Outcome`, where `Outcome`
12
+ * carries the HTTP status the JSON route answers with. The MCP adapter reads
13
+ * the same status: >= 400 becomes a tool error, anything else the tool result.
14
+ *
15
+ * Reads (list/search/get/…) are NOT here — they are single `store.*` calls
16
+ * and both adapters make them directly.
17
+ */
18
+
19
+ /**
20
+ * A command's result, in the JSON adapter's vocabulary because that adapter
21
+ * is the reference: `status` is the HTTP status `/api/*` answers with, `body`
22
+ * the JSON it renders.
23
+ */
24
+ export interface Outcome {
25
+ status: number
26
+ body: Record<string, unknown>
27
+ }
28
+
29
+ export interface SendBody {
30
+ to: string
31
+ subject: string
32
+ text?: string
33
+ html?: string
34
+ from?: string
35
+ /** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
36
+ inReplyTo?: string
37
+ /**
38
+ * ISO timestamp: instead of sending now, queue the message for the DO
39
+ * alarm to dispatch at (or shortly after) this time.
40
+ */
41
+ sendAt?: string
42
+ }
43
+
44
+ export interface SendEnv extends MailEnv {
45
+ DEFAULT_FROM?: string
46
+ }
47
+
48
+ /**
49
+ * Send now, or queue for the DO alarm when `sendAt` is set. Validates,
50
+ * dispatches, records the outbound row, and emits the message.sent webhook.
51
+ */
52
+ export async function send(env: SendEnv, store: InboxStore, body: SendBody): Promise<Outcome> {
53
+ if (!body.to || !body.subject || (!body.text && !body.html)) {
54
+ return { status: 400, body: { error: 'required: to, subject, and text or html' } }
55
+ }
56
+ const from = body.from ?? env.DEFAULT_FROM
57
+ if (!from) {
58
+ return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or pass from)' } }
59
+ }
60
+
61
+ // Email Sending only accepts whitelisted custom headers (a Message-ID of
62
+ // our own is rejected), so the wire Message-ID is provider-chosen and
63
+ // unknown to us. We store a synthetic one for OUR send chain; recipient
64
+ // replies thread via the subject+participant fallback.
65
+ const id = newId()
66
+ const messageId = `${id}@${from.split('@')[1] ?? 'localhost'}`
67
+ const inReplyTo = normalizeMsgId(body.inReplyTo)
68
+ const text = body.text ?? ''
69
+ const snippet = makeSnippet(text, body.html ?? '')
70
+
71
+ // sendAt → queue for the DO alarm instead of dispatching now.
72
+ if (body.sendAt !== undefined) {
73
+ const at = new Date(body.sendAt)
74
+ if (Number.isNaN(at.getTime())) {
75
+ return { status: 400, body: { error: 'sendAt is not a valid date' } }
76
+ }
77
+ await store.insert({
78
+ id,
79
+ status: 'scheduled',
80
+ scheduled_at: at.toISOString(),
81
+ direction: 'outbound',
82
+ in_reply_to: inReplyTo,
83
+ message_id: messageId,
84
+ from_addr: from,
85
+ to_addr: body.to,
86
+ subject: body.subject,
87
+ date: at.toISOString(),
88
+ snippet,
89
+ text_body: text,
90
+ html_body: body.html ?? '',
91
+ r2_key: '',
92
+ attachments_json: '[]',
93
+ size: text.length + (body.html?.length ?? 0),
94
+ })
95
+ return { status: 202, body: { ok: true, id, status: 'scheduled', sendAt: at.toISOString() } }
96
+ }
97
+
98
+ try {
99
+ await sendMail(env, {
100
+ from,
101
+ to: body.to,
102
+ subject: body.subject,
103
+ text: body.text,
104
+ html: body.html,
105
+ inReplyTo,
106
+ })
107
+ } catch (err) {
108
+ return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
109
+ }
110
+
111
+ // Record the outbound message so the inbox shows both sides of a
112
+ // conversation. No raw MIME (we never see the provider's final wire form),
113
+ // so r2_key stays empty and /raw 404s for these.
114
+ const { threadId } = await store.insert({
115
+ id,
116
+ direction: 'outbound',
117
+ in_reply_to: inReplyTo,
118
+ message_id: messageId,
119
+ from_addr: from,
120
+ to_addr: body.to,
121
+ subject: body.subject,
122
+ date: new Date().toISOString(),
123
+ snippet,
124
+ text_body: text,
125
+ html_body: body.html ?? '',
126
+ r2_key: '',
127
+ attachments_json: '[]',
128
+ size: text.length + (body.html?.length ?? 0),
129
+ })
130
+ await emitWebhook(env, 'message.sent', {
131
+ id,
132
+ threadId,
133
+ from,
134
+ to: body.to,
135
+ subject: body.subject,
136
+ snippet,
137
+ direction: 'outbound',
138
+ })
139
+ return { status: 200, body: { ok: true, id, from, to: body.to, messageId, threadId } }
140
+ }
141
+
142
+ /** Send an existing draft: validate completeness, dispatch, flip to sent. */
143
+ export async function sendDraft(
144
+ env: SendEnv,
145
+ store: InboxStore,
146
+ draftId: string,
147
+ ): Promise<Outcome> {
148
+ const draft = await store.get(draftId)
149
+ if (!draft || draft.status !== 'draft') return { status: 404, body: { error: 'not a draft' } }
150
+ const from = draft.from_addr || env.DEFAULT_FROM
151
+ if (!from) {
152
+ return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or the draft from)' } }
153
+ }
154
+ if (!draft.to_addr || !draft.subject || (!draft.text_body && !draft.html_body)) {
155
+ return { status: 400, body: { error: 'draft incomplete: needs to, subject, and text or html' } }
156
+ }
157
+ try {
158
+ await sendMail(env, {
159
+ from,
160
+ to: draft.to_addr,
161
+ subject: draft.subject,
162
+ text: draft.text_body || undefined,
163
+ html: draft.html_body || undefined,
164
+ inReplyTo: draft.in_reply_to,
165
+ })
166
+ } catch (err) {
167
+ return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
168
+ }
169
+ // Persist the from that was actually used (may have come from
170
+ // DEFAULT_FROM), then flip the row to sent — thread resolves NOW.
171
+ if (from !== draft.from_addr) await store.updateDraft(draftId, { from_addr: from })
172
+ const sent = await store.markDraftSent(draftId, new Date().toISOString())
173
+ if (!sent) return { status: 500, body: { error: 'draft vanished during send' } }
174
+ await emitWebhook(env, 'message.sent', {
175
+ id: draftId,
176
+ threadId: sent.threadId,
177
+ from,
178
+ to: draft.to_addr,
179
+ subject: draft.subject,
180
+ snippet: draft.snippet,
181
+ direction: 'outbound',
182
+ })
183
+ return {
184
+ status: 200,
185
+ body: { ok: true, id: draftId, from, to: draft.to_addr, threadId: sent.threadId },
186
+ }
187
+ }
188
+
189
+ /**
190
+ * A draft's fields as an adapter hands them in. Every one is optional: a
191
+ * draft may be partial, and completeness is enforced at send time by
192
+ * {@link sendDraft}.
193
+ */
194
+ export interface DraftBody {
195
+ to?: string
196
+ subject?: string
197
+ text?: string
198
+ html?: string
199
+ from?: string
200
+ /** RFC 5322 Message-ID of the message being replied to. */
201
+ inReplyTo?: string
202
+ }
203
+
204
+ /** Store an outbound message without sending it. */
205
+ export async function createDraft(
206
+ env: SendEnv,
207
+ store: InboxStore,
208
+ body: DraftBody,
209
+ ): Promise<Outcome> {
210
+ const id = newId()
211
+ const from = body.from ?? env.DEFAULT_FROM ?? ''
212
+ const text = body.text ?? ''
213
+ await store.insert({
214
+ id,
215
+ status: 'draft',
216
+ direction: 'outbound',
217
+ in_reply_to: normalizeMsgId(body.inReplyTo),
218
+ message_id: `${id}@${from.split('@')[1] || 'localhost'}`,
219
+ from_addr: from,
220
+ to_addr: body.to ?? '',
221
+ subject: body.subject ?? '',
222
+ date: new Date().toISOString(),
223
+ snippet: makeSnippet(text, body.html ?? ''),
224
+ text_body: text,
225
+ html_body: body.html ?? '',
226
+ r2_key: '',
227
+ attachments_json: '[]',
228
+ size: text.length + (body.html?.length ?? 0),
229
+ })
230
+ return { status: 201, body: { ok: true, id, status: 'draft' } }
231
+ }
232
+
233
+ /**
234
+ * Patch an unsent draft: only the fields present change, and `snippet` is
235
+ * recomputed whenever either body was touched. Which rows may be patched at
236
+ * all is the DO's rule (`updateDraft` refuses anything but a draft), not this
237
+ * command's — the command only translates the adapter's field names.
238
+ *
239
+ * Known wart, carried verbatim from the two adapter copies this replaced and
240
+ * left alone here so the refactor stays byte-identical: the snippet is derived
241
+ * from the PATCH, not from the patched row. Patching only `html` on a draft
242
+ * that already has a `text_body` therefore writes a snippet taken from the new
243
+ * html while the text part — the one `makeSnippet` would have preferred, and
244
+ * the one that actually goes out — is unchanged. Fixing it needs the command
245
+ * to read the row first (an extra DO round-trip), which is a behaviour change,
246
+ * not a refactor. `commands.test.ts` pins the current behaviour so a fix is a
247
+ * deliberate edit to that test rather than a silent one.
248
+ */
249
+ export async function updateDraft(
250
+ store: InboxStore,
251
+ id: string,
252
+ patch: DraftBody,
253
+ ): Promise<Outcome> {
254
+ const { text, html } = patch
255
+ const fields: DraftFields = {
256
+ ...(patch.from !== undefined ? { from_addr: patch.from } : {}),
257
+ ...(patch.to !== undefined ? { to_addr: patch.to } : {}),
258
+ ...(patch.subject !== undefined ? { subject: patch.subject } : {}),
259
+ ...(text !== undefined ? { text_body: text } : {}),
260
+ ...(html !== undefined ? { html_body: html } : {}),
261
+ ...(patch.inReplyTo !== undefined ? { in_reply_to: normalizeMsgId(patch.inReplyTo) } : {}),
262
+ ...(text !== undefined || html !== undefined
263
+ ? { snippet: makeSnippet(text ?? '', html ?? '') }
264
+ : {}),
265
+ }
266
+ const updated = await store.updateDraft(id, fields)
267
+ return updated
268
+ ? { status: 200, body: { ok: true, id } }
269
+ : { status: 404, body: { error: 'not a draft' } }
270
+ }
271
+
272
+ /**
273
+ * Delete a message of any status, plus its raw MIME blob.
274
+ *
275
+ * `store.delete` answers with three distinct values and all three matter:
276
+ * `null` (no such row), `''` (deleted, but it never had raw MIME — a draft,
277
+ * a scheduled row, or anything outbound) and a key (delete the R2 object
278
+ * too). The JSON route used to test `!r2Key`, which folded `''` into "not
279
+ * found" and answered 404 for a row it had just deleted; the MCP tool tested
280
+ * `=== null` and was right. This command takes the MCP reading.
281
+ */
282
+ export async function deleteMessage(
283
+ env: { RAW: R2Bucket },
284
+ store: InboxStore,
285
+ id: string,
286
+ ): Promise<Outcome> {
287
+ const r2Key = await store.delete(id)
288
+ if (r2Key === null) return { status: 404, body: { error: 'not found' } }
289
+ if (r2Key) await env.RAW.delete(r2Key)
290
+ return { status: 200, body: { ok: true } }
291
+ }
292
+
293
+ /** Cancel a pending scheduled send, or dismiss a failed one. Deletes the row. */
294
+ export async function cancelScheduled(store: InboxStore, id: string): Promise<Outcome> {
295
+ const cancelled = await store.cancelScheduled(id)
296
+ return cancelled
297
+ ? { status: 200, body: { ok: true } }
298
+ : { status: 404, body: { error: 'not a scheduled send' } }
299
+ }
@@ -75,6 +75,57 @@ export interface InsertMessage {
75
75
  scheduled_at?: string
76
76
  }
77
77
 
78
+ /** Fields of a draft that `updateDraft` may change. */
79
+ export type DraftFields = Partial<
80
+ Pick<
81
+ InsertMessage,
82
+ 'from_addr' | 'to_addr' | 'subject' | 'text_body' | 'html_body' | 'in_reply_to' | 'snippet'
83
+ >
84
+ >
85
+
86
+ /**
87
+ * A value the caller must await but the implementation may return
88
+ * synchronously: the Inbox class's methods are plain sync SQLite calls, while
89
+ * the same methods reached through a `DurableObjectStub` come back as
90
+ * Promises. Both satisfy `InboxStore`, and every caller awaits.
91
+ */
92
+ type Awaitable<T> = T | Promise<T>
93
+
94
+ /**
95
+ * The narrow view of the Inbox that the commands and the two adapters call.
96
+ *
97
+ * It exists as an interface rather than as `DurableObjectStub<Inbox>` because
98
+ * that type expands workers-types' recursive RPC serialization generics inside
99
+ * every `registerTool` inference in `mcp.ts` and trips TS2589 ("type
100
+ * instantiation is excessively deep"). `mcp.ts` used to keep a hand-written
101
+ * copy of these signatures; the copy lives here now and `Inbox implements
102
+ * InboxStore` is what stops it drifting from the class.
103
+ *
104
+ * It is also the seam the tests use: `worker/commands.test.ts` drives both
105
+ * adapters against an in-memory fake of exactly this surface.
106
+ */
107
+ export interface InboxStore {
108
+ list(
109
+ limit: number,
110
+ cursor?: string,
111
+ label?: string,
112
+ ): Awaitable<{ messages: MessageMeta[]; nextCursor: string | null }>
113
+ listThreads(
114
+ limit: number,
115
+ cursor?: string,
116
+ ): Awaitable<{ threads: ThreadMeta[]; nextCursor: string | null }>
117
+ getThread(threadId: string): Awaitable<MessageFull[]>
118
+ get(id: string): Awaitable<MessageFull | null>
119
+ search(q: string, limit: number): Awaitable<MessageMeta[]>
120
+ insert(msg: InsertMessage): Awaitable<{ threadId: string }>
121
+ listDrafts(limit: number): Awaitable<MessageMeta[]>
122
+ updateDraft(id: string, fields: DraftFields): Awaitable<boolean>
123
+ markDraftSent(id: string, date: string): Awaitable<{ threadId: string } | null>
124
+ listScheduled(limit: number): Awaitable<ScheduledMeta[]>
125
+ cancelScheduled(id: string): Awaitable<boolean>
126
+ delete(id: string): Awaitable<string | null>
127
+ }
128
+
78
129
  /** Strip Re:/Fwd: prefixes + whitespace so replies fall into the same thread. */
79
130
  function normalizeSubject(subject: string): string {
80
131
  return subject
@@ -84,7 +135,7 @@ function normalizeSubject(subject: string): string {
84
135
  .toLowerCase()
85
136
  }
86
137
 
87
- export class Inbox extends DurableObject<MailEnv> {
138
+ export class Inbox extends DurableObject<MailEnv> implements InboxStore {
88
139
  private sql: SqlStorage
89
140
 
90
141
  constructor(ctx: DurableObjectState, env: MailEnv) {
@@ -340,15 +391,7 @@ export class Inbox extends DurableObject<MailEnv> {
340
391
  }
341
392
 
342
393
  /** Update an unsent draft's editable fields. Returns false if not a draft. */
343
- updateDraft(
344
- id: string,
345
- fields: Partial<
346
- Pick<
347
- InsertMessage,
348
- 'from_addr' | 'to_addr' | 'subject' | 'text_body' | 'html_body' | 'in_reply_to' | 'snippet'
349
- >
350
- >,
351
- ): boolean {
394
+ updateDraft(id: string, fields: DraftFields): boolean {
352
395
  const row = this.sql
353
396
  .exec(`SELECT status FROM messages WHERE id = ?`, id)
354
397
  .toArray()[0] as unknown as { status: string } | undefined
@@ -3,18 +3,23 @@
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.
6
- * - `/api/*`: bearer-authed JSON API (list / read / raw / delete / send).
6
+ * - `/api/*`: bearer-authed JSON API — handled by `api.ts`.
7
+ * - `/mcp`: the MCP server over the same operations — handled by `mcp.ts`.
7
8
  * - Everything else: the static UI in public/ (ASSETS binding).
9
+ *
10
+ * This file is the runtime entry only: the Env, the bearer check, inbound mail
11
+ * and the dispatch. Both adapters live beside it so a test can load them —
12
+ * see the note atop `api.ts`.
8
13
  */
9
14
  import PostalMime from 'postal-mime'
10
- import { Inbox } from './inbox-do'
15
+ import { type ApiEnv, handleApi, json } from './api'
16
+ import { Inbox, type InboxStore } from './inbox-do'
11
17
  import { handleMcp } from './mcp'
12
- import { type SendBody, performDraftSend, performSend } from './send-op'
13
18
  import { type SendEmailBinding, emitWebhook, makeSnippet, newId, normalizeMsgId } from './shared'
14
19
 
15
20
  export { Inbox }
16
21
 
17
- export interface Env {
22
+ export interface Env extends ApiEnv {
18
23
  ASSETS: { fetch: (request: Request) => Promise<Response> }
19
24
  INBOX: DurableObjectNamespace<Inbox>
20
25
  RAW: R2Bucket
@@ -53,10 +58,6 @@ async function authorized(request: Request, env: Env): Promise<boolean> {
53
58
  return crypto.subtle.timingSafeEqual(a, b)
54
59
  }
55
60
 
56
- function json(data: unknown, status = 200): Response {
57
- return Response.json(data, { status, headers: { 'cache-control': 'no-store' } })
58
- }
59
-
60
61
  function inboxStub(env: Env) {
61
62
  return env.INBOX.get(env.INBOX.idFromName('inbox'))
62
63
  }
@@ -179,204 +180,16 @@ export default {
179
180
  return json({ error: 'unauthorized' }, 401)
180
181
  }
181
182
 
182
- const stub = inboxStub(env)
183
+ // The DO stub reaches both adapters as an InboxStore: `DurableObjectStub<
184
+ // Inbox>` expands workers-types' recursive RPC generics inside mcp.ts's
185
+ // registerTool inference and trips TS2589. This is the one cast.
186
+ const store = inboxStub(env) as unknown as InboxStore
183
187
 
184
188
  // POST/GET/DELETE /mcp — MCP server (Streamable HTTP), same bearer token
185
189
  if (pathname === '/mcp') {
186
- return handleMcp(request, { env, stub })
187
- }
188
-
189
- // GET /api/messages?limit=&cursor=&label=
190
- if (pathname === '/api/messages' && request.method === 'GET') {
191
- const limit = Number(url.searchParams.get('limit') ?? '50')
192
- const cursor = url.searchParams.get('cursor') ?? undefined
193
- const label = url.searchParams.get('label') ?? undefined
194
- return json(await stub.list(Number.isFinite(limit) ? limit : 50, cursor, label))
195
- }
196
-
197
- // GET /api/search?q=&limit= — keyword match over subject + text body
198
- if (pathname === '/api/search' && request.method === 'GET') {
199
- const q = url.searchParams.get('q') ?? ''
200
- if (!q.trim()) return json({ error: 'required: q' }, 400)
201
- const limit = Number(url.searchParams.get('limit') ?? '50')
202
- return json({ messages: await stub.search(q.trim(), Number.isFinite(limit) ? limit : 50) })
203
- }
204
-
205
- // GET /api/threads?limit=&cursor= — newest-first, one row per thread
206
- if (pathname === '/api/threads' && request.method === 'GET') {
207
- const limit = Number(url.searchParams.get('limit') ?? '50')
208
- const cursor = url.searchParams.get('cursor') ?? undefined
209
- return json(await stub.listThreads(Number.isFinite(limit) ? limit : 50, cursor))
210
- }
211
-
212
- // GET /api/threads/:id — all messages in the thread, oldest-first
213
- const threadMatch = pathname.match(/^\/api\/threads\/([^/]+)$/)
214
- if (threadMatch && request.method === 'GET') {
215
- const messages = await stub.getThread(threadMatch[1]!)
216
- return messages.length ? json({ messages }) : json({ error: 'not found' }, 404)
217
- }
218
-
219
- // POST /api/send — immediate, or queued for the DO alarm when sendAt set
220
- if (pathname === '/api/send' && request.method === 'POST') {
221
- let body: SendBody
222
- try {
223
- body = (await request.json()) as SendBody
224
- } catch {
225
- return json({ error: 'invalid JSON body' }, 400)
226
- }
227
- const outcome = await performSend(env, stub, body)
228
- return json(outcome.body, outcome.status)
229
- }
230
-
231
- // GET /api/scheduled — pending + failed scheduled sends, soonest first
232
- if (pathname === '/api/scheduled' && request.method === 'GET') {
233
- const limit = Number(url.searchParams.get('limit') ?? '50')
234
- return json({ scheduled: await stub.listScheduled(Number.isFinite(limit) ? limit : 50) })
235
- }
236
-
237
- // DELETE /api/scheduled/:id — cancel a pending (or dismiss a failed) send
238
- const schedMatch = pathname.match(/^\/api\/scheduled\/([^/]+)$/)
239
- if (schedMatch && request.method === 'DELETE') {
240
- const cancelled = await stub.cancelScheduled(schedMatch[1]!)
241
- return cancelled ? json({ ok: true }) : json({ error: 'not a scheduled send' }, 404)
242
- }
243
-
244
- // POST /api/drafts — store an outbound message without sending it
245
- if (pathname === '/api/drafts' && request.method === 'POST') {
246
- let body: SendBody
247
- try {
248
- body = (await request.json()) as SendBody
249
- } catch {
250
- return json({ error: 'invalid JSON body' }, 400)
251
- }
252
- // Drafts may be partial — completeness is enforced at send time.
253
- const id = newId()
254
- const from = body.from ?? env.DEFAULT_FROM ?? ''
255
- const text = body.text ?? ''
256
- await stub.insert({
257
- id,
258
- status: 'draft',
259
- direction: 'outbound',
260
- in_reply_to: normalizeMsgId(body.inReplyTo),
261
- message_id: `${id}@${from.split('@')[1] || 'localhost'}`,
262
- from_addr: from,
263
- to_addr: body.to ?? '',
264
- subject: body.subject ?? '',
265
- date: new Date().toISOString(),
266
- snippet: makeSnippet(text, body.html ?? ''),
267
- text_body: text,
268
- html_body: body.html ?? '',
269
- r2_key: '',
270
- attachments_json: '[]',
271
- size: text.length + (body.html?.length ?? 0),
272
- })
273
- return json({ ok: true, id, status: 'draft' }, 201)
274
- }
275
-
276
- // GET /api/drafts
277
- if (pathname === '/api/drafts' && request.method === 'GET') {
278
- const limit = Number(url.searchParams.get('limit') ?? '50')
279
- return json({ drafts: await stub.listDrafts(Number.isFinite(limit) ? limit : 50) })
280
- }
281
-
282
- // PUT /api/drafts/:id | POST /api/drafts/:id/send
283
- const draftMatch = pathname.match(/^\/api\/drafts\/([^/]+)(\/send)?$/)
284
- if (draftMatch) {
285
- const [, draftId, sendSuffix] = draftMatch
286
-
287
- if (!sendSuffix && request.method === 'PUT') {
288
- let body: SendBody
289
- try {
290
- body = (await request.json()) as SendBody
291
- } catch {
292
- return json({ error: 'invalid JSON body' }, 400)
293
- }
294
- const text = body.text
295
- const html = body.html
296
- const updated = await stub.updateDraft(draftId!, {
297
- ...(body.from !== undefined ? { from_addr: body.from } : {}),
298
- ...(body.to !== undefined ? { to_addr: body.to } : {}),
299
- ...(body.subject !== undefined ? { subject: body.subject } : {}),
300
- ...(text !== undefined ? { text_body: text } : {}),
301
- ...(html !== undefined ? { html_body: html } : {}),
302
- ...(body.inReplyTo !== undefined ? { in_reply_to: normalizeMsgId(body.inReplyTo) } : {}),
303
- ...(text !== undefined || html !== undefined
304
- ? { snippet: makeSnippet(text ?? '', html ?? '') }
305
- : {}),
306
- })
307
- return updated ? json({ ok: true, id: draftId }) : json({ error: 'not a draft' }, 404)
308
- }
309
-
310
- if (sendSuffix && request.method === 'POST') {
311
- const outcome = await performDraftSend(env, stub, draftId!)
312
- return json(outcome.body, outcome.status)
313
- }
314
- if (!sendSuffix && request.method === 'GET') {
315
- const draft = await stub.get(draftId!)
316
- return draft && draft.status === 'draft' ? json(draft) : json({ error: 'not a draft' }, 404)
317
- }
318
- if (!sendSuffix && request.method === 'DELETE') {
319
- const draft = await stub.get(draftId!)
320
- if (!draft || draft.status !== 'draft') return json({ error: 'not a draft' }, 404)
321
- await stub.delete(draftId!)
322
- return json({ ok: true })
323
- }
324
- }
325
-
326
- // GET /api/messages/:id/attachments/:n — raw bytes of one attachment.
327
- // Re-parses the R2 MIME blob per request (cheap at the 5 MiB cap) rather
328
- // than pre-splitting attachments at write time.
329
- const attMatch = pathname.match(/^\/api\/messages\/([^/]+)\/attachments\/(\d+)$/)
330
- if (attMatch && request.method === 'GET') {
331
- const msg = await stub.get(attMatch[1]!)
332
- if (!msg) return json({ error: 'not found' }, 404)
333
- if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
334
- const obj = await env.RAW.get(msg.r2_key)
335
- if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
336
- const parsed = await PostalMime.parse(await obj.arrayBuffer())
337
- const n = Number(attMatch[2])
338
- const att = (parsed.attachments ?? [])[n]
339
- if (!att) return json({ error: `no attachment at index ${n}` }, 404)
340
- const body =
341
- typeof att.content === 'string' ? new TextEncoder().encode(att.content) : att.content
342
- return new Response(body, {
343
- headers: {
344
- 'content-type': att.mimeType || 'application/octet-stream',
345
- 'content-disposition': `attachment; filename="${(att.filename ?? 'attachment').replace(/["\r\n]/g, '')}"`,
346
- 'cache-control': 'no-store',
347
- },
348
- })
349
- }
350
-
351
- // /api/messages/:id[/raw]
352
- const match = pathname.match(/^\/api\/messages\/([^/]+)(\/raw)?$/)
353
- if (match) {
354
- const [, id, rawSuffix] = match
355
-
356
- if (rawSuffix && request.method === 'GET') {
357
- const msg = await stub.get(id!)
358
- if (!msg) return json({ error: 'not found' }, 404)
359
- if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
360
- const obj = await env.RAW.get(msg.r2_key)
361
- if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
362
- return new Response(obj.body, {
363
- headers: { 'content-type': 'message/rfc822', 'cache-control': 'no-store' },
364
- })
365
- }
366
-
367
- if (!rawSuffix && request.method === 'GET') {
368
- const msg = await stub.get(id!)
369
- return msg ? json(msg) : json({ error: 'not found' }, 404)
370
- }
371
-
372
- if (!rawSuffix && request.method === 'DELETE') {
373
- const r2Key = await stub.delete(id!)
374
- if (!r2Key) return json({ error: 'not found' }, 404)
375
- await env.RAW.delete(r2Key)
376
- return json({ ok: true })
377
- }
190
+ return handleMcp(request, { env, store })
378
191
  }
379
192
 
380
- return json({ error: 'not found' }, 404)
193
+ return handleApi(request, { env, store })
381
194
  },
382
195
  }