@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.
- package/CHANGELOG.md +117 -6
- package/package.json +5 -2
- package/src/commands/add.ts +13 -0
- package/src/commands/apply.ts +33 -9
- package/src/commands/destroy.ts +1 -1
- package/src/commands/init.ts +1 -0
- package/src/engine/apply.ts +110 -22
- package/src/engine/destroy.ts +183 -14
- package/src/engine/discover.ts +1 -1
- package/src/engine/resolve.ts +113 -14
- package/src/utils/copy-template.ts +10 -0
- package/templates/CLAUDE.md +1 -1
- package/templates/apps/inbox/package.json +3 -1
- package/templates/apps/inbox/tsconfig.json +3 -1
- package/templates/apps/inbox/worker/api.ts +197 -0
- package/templates/apps/inbox/worker/commands.ts +299 -0
- package/templates/apps/inbox/worker/inbox-do.ts +53 -10
- package/templates/apps/inbox/worker/index.ts +15 -202
- package/templates/apps/inbox/worker/mcp.ts +49 -100
- package/templates/infra/modules/cloudflare/index.ts +29 -73
- package/templates/infra/modules/cloudflare-access/index.ts +3 -3
- package/templates/infra/modules/cloudflare-api/index.ts +144 -32
- package/templates/infra/modules/cloudflare-api/registry.json +1 -1
- package/templates/infra/modules/cloudflare-email/index.ts +103 -144
- package/templates/infra/modules/cloudflare-email/registry.json +1 -1
- package/templates/infra/modules/cloudflare-token/index.ts +10 -32
- package/templates/infra/modules/cloudflare-token/registry.json +1 -1
- package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
- package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
- package/templates/infra/modules/fly/index.ts +17 -42
- package/templates/infra/modules/fly/registry.json +1 -1
- package/templates/infra/modules/host-file/index.ts +6 -7
- package/templates/infra/modules/provision-core/index.ts +21 -15
- package/templates/infra/modules/r2/index.ts +40 -71
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/modules/remote-provision/index.ts +1 -3
- package/templates/infra/modules/turso/index.ts +2 -15
- package/templates/infra/modules/vm-provision/index.ts +10 -3
- package/templates/infra/src/context.ts +115 -0
- package/templates/infra/src/define-module.ts +41 -2
- package/templates/infra/src/index.ts +11 -1
- package/templates/infra/src/types.ts +85 -3
- package/src/commands/add-registry.test.ts +0 -92
- package/src/commands/secret.test.ts +0 -717
- package/src/commands/vendor-mode.test.ts +0 -183
- package/src/infra-types.ts +0 -38
- package/src/utils/subtree.test.ts +0 -127
- package/templates/apps/inbox/worker/send-op.ts +0 -174
package/src/engine/resolve.ts
CHANGED
|
@@ -1,22 +1,119 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { legacyConfigEphemeral } from '../../templates/infra/src/define-module'
|
|
2
|
+
import type { ModuleInstance } from '../../templates/infra/src/types'
|
|
3
|
+
|
|
4
|
+
export interface ResolveOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Apply/destroy only these instances (plus, for apply, their transitive
|
|
7
|
+
* imports). A bare string is one of them.
|
|
8
|
+
*
|
|
9
|
+
* Plural because CI scopes a production apply to what a push actually
|
|
10
|
+
* touched, and a push routinely touches two — running the CLI once per name
|
|
11
|
+
* would re-decrypt the environment and re-apply the shared dependencies of
|
|
12
|
+
* each, turning a saving into a slower, noisier deploy.
|
|
13
|
+
*/
|
|
14
|
+
target?: string | string[]
|
|
15
|
+
/** Where the instances came from, for error messages. */
|
|
16
|
+
envLabel?: string
|
|
17
|
+
/**
|
|
18
|
+
* Refuse an import naming an instance the environment does not contain.
|
|
19
|
+
* Default true — and false on the destroy path, which is a CLEANUP path: an
|
|
20
|
+
* environment whose graph has gone bad is exactly the one you need to be able
|
|
21
|
+
* to tear down, and refusing strands every resource in it. Destroy never
|
|
22
|
+
* needed the missing instance's outputs; the edge is simply skipped, which is
|
|
23
|
+
* what the whole engine used to do.
|
|
24
|
+
*/
|
|
25
|
+
assertImports?: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function resolveOrder(
|
|
29
|
+
instances: ModuleInstance[],
|
|
30
|
+
opts: ResolveOptions = {},
|
|
31
|
+
): ModuleInstance[] {
|
|
32
|
+
if (opts.assertImports !== false) assertImportsDiscovered(instances, opts.envLabel)
|
|
2
33
|
|
|
3
|
-
export function resolveOrder(instances: ModuleInstance[], target?: string): ModuleInstance[] {
|
|
4
34
|
let toProcess = instances
|
|
5
35
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
)
|
|
36
|
+
const targets = typeof opts.target === 'string' ? [opts.target] : (opts.target ?? [])
|
|
37
|
+
|
|
38
|
+
if (targets.length > 0) {
|
|
39
|
+
const selected = new Map<string, ModuleInstance>()
|
|
40
|
+
for (const target of targets) {
|
|
41
|
+
const targetInstance = instances.find((i) => i.name === target)
|
|
42
|
+
if (!targetInstance) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
`Instance "${target}" not found. Available: ${instances.map((i) => i.name).join(', ')}`,
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
// Union, not concatenation: two targets that share a dependency would
|
|
48
|
+
// otherwise list it twice, and the sort counts an instance's edges once.
|
|
49
|
+
for (const dep of collectTransitiveDeps(targetInstance)) selected.set(dep.name, dep)
|
|
12
50
|
}
|
|
13
|
-
toProcess =
|
|
51
|
+
toProcess = Array.from(selected.values())
|
|
14
52
|
}
|
|
15
53
|
|
|
16
54
|
return topologicalSort(toProcess)
|
|
17
55
|
}
|
|
18
56
|
|
|
19
|
-
|
|
57
|
+
/**
|
|
58
|
+
* An import naming an instance the environment does not contain is a hard
|
|
59
|
+
* error, not a shrug.
|
|
60
|
+
*
|
|
61
|
+
* It used to be two silent ones that compounded: the sort skipped the edge, so
|
|
62
|
+
* the importer could run first, and the apply loop then wrote `undefined` into
|
|
63
|
+
* `ctx.imports` under that name. The module downstream reported a missing
|
|
64
|
+
* OUTPUT — "instance X doesn't emit Y" — for an instance that was never there
|
|
65
|
+
* at all, which sends the reader to the wrong file.
|
|
66
|
+
*/
|
|
67
|
+
function assertImportsDiscovered(instances: ModuleInstance[], envLabel?: string): void {
|
|
68
|
+
const known = new Set(instances.map((i) => i.name))
|
|
69
|
+
const where = envLabel ?? 'this environment'
|
|
70
|
+
for (const inst of instances) {
|
|
71
|
+
for (const dep of inst.imports) {
|
|
72
|
+
if (!known.has(dep.name)) {
|
|
73
|
+
throw new Error(`Instance "${inst.name}" imports "${dep.name}", which is not in ${where}`)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Whether this instance is ephemeral.
|
|
81
|
+
*
|
|
82
|
+
* `ephemeral` is WRITTEN by `defineModule` — which a subtree consumer vendors at
|
|
83
|
+
* `vendor/zbc/src/` and moves with `zbc update` — and READ here, in the engine
|
|
84
|
+
* the npm CLI ships. The two version independently, so an instance built by a
|
|
85
|
+
* `define-module.ts` older than this CLI has no `ephemeral` property at all. The
|
|
86
|
+
* engine repeats the legacy fallback rather than reading `undefined` as "no",
|
|
87
|
+
* which would silently make every preview resource permanent.
|
|
88
|
+
*
|
|
89
|
+
* The reverse skew — a newer vendored subtree under an older CLI, whose engine
|
|
90
|
+
* knows nothing of instance-level `ephemeral` — cannot be fixed from here; `zbc
|
|
91
|
+
* update` moving ahead of the CLI is what the version pin in `zbc init
|
|
92
|
+
* --subtree` exists to prevent.
|
|
93
|
+
*/
|
|
94
|
+
export function isEphemeral(instance: ModuleInstance): boolean {
|
|
95
|
+
const declared = (instance as { ephemeral?: boolean }).ephemeral
|
|
96
|
+
return declared ?? legacyConfigEphemeral(instance.moduleName, instance.config)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* An ephemeral instance of a module with no `destroy` is a contradiction, and
|
|
101
|
+
* the engine refuses it before it applies anything — including the instances
|
|
102
|
+
* that sort ahead of it. Silently applying an "ephemeral" resource that is
|
|
103
|
+
* never torn down is exactly what `cloudflare-token` did for as long as it
|
|
104
|
+
* declared the flag and never read it.
|
|
105
|
+
*/
|
|
106
|
+
export function assertEphemeralDestroyable(instances: ModuleInstance[]): void {
|
|
107
|
+
for (const inst of instances) {
|
|
108
|
+
if (isEphemeral(inst) && !inst._definition.destroy) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`Instance "${inst.name}" is ephemeral but module "${inst.moduleName}" has no destroy`,
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function collectTransitiveDeps(instance: ModuleInstance): ModuleInstance[] {
|
|
20
117
|
const collected = new Set<string>()
|
|
21
118
|
const result: ModuleInstance[] = []
|
|
22
119
|
|
|
@@ -46,10 +143,12 @@ function topologicalSort(instances: ModuleInstance[]): ModuleInstance[] {
|
|
|
46
143
|
|
|
47
144
|
for (const inst of instances) {
|
|
48
145
|
for (const dep of inst.imports) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
146
|
+
// On the apply path every edge is present — `assertImportsDiscovered`
|
|
147
|
+
// covers the whole environment, and a targeted run carries the transitive
|
|
148
|
+
// closure. The skip is for the destroy path, which does not assert.
|
|
149
|
+
if (!nameToInstance.has(dep.name)) continue
|
|
150
|
+
adjacency.get(dep.name)!.push(inst.name)
|
|
151
|
+
inDegree.set(inst.name, (inDegree.get(inst.name) ?? 0) + 1)
|
|
53
152
|
}
|
|
54
153
|
}
|
|
55
154
|
|
|
@@ -8,6 +8,15 @@ interface CopyOptions {
|
|
|
8
8
|
skipIfExists?: boolean
|
|
9
9
|
/** Directory/file basenames to skip (e.g. ['modules']). */
|
|
10
10
|
exclude?: string[]
|
|
11
|
+
/**
|
|
12
|
+
* Skip `*.test.ts`. On for the infra engine and its modules, whose tests are
|
|
13
|
+
* ours and not part of what a consumer is scaffolded — the published tarball
|
|
14
|
+
* already drops them (`!templates/**\/*.test.ts` in the manifest's `files`),
|
|
15
|
+
* so this is what makes running the CLI from a checkout produce the same
|
|
16
|
+
* tree. OFF for app templates: that is code the consumer owns and maintains,
|
|
17
|
+
* and its tests go with it.
|
|
18
|
+
*/
|
|
19
|
+
excludeTests?: boolean
|
|
11
20
|
}
|
|
12
21
|
|
|
13
22
|
function substitute(body: string, vars: Record<string, string>): string {
|
|
@@ -58,6 +67,7 @@ export async function copyTemplateDir(
|
|
|
58
67
|
|
|
59
68
|
for (const entry of entries) {
|
|
60
69
|
if (exclude.has(entry.name)) continue
|
|
70
|
+
if (opts.excludeTests && entry.isFile() && entry.name.endsWith('.test.ts')) continue
|
|
61
71
|
const srcPath = path.join(sourceDir, entry.name)
|
|
62
72
|
const destName = rename[entry.name] ?? entry.name
|
|
63
73
|
const destPath = path.join(destDir, destName)
|
package/templates/CLAUDE.md
CHANGED
|
@@ -16,7 +16,7 @@ This project uses [zbc](https://github.com/Zabaca/zbc) for infrastructure scaffo
|
|
|
16
16
|
- `bun install` — install dependencies
|
|
17
17
|
- `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`inbox` — an agent-accessible email inbox; `secret-relay` — the browser-based secret request relay; `warehouse` — a dlt+dbt-duckdb data warehouse/BI pipeline; each auto-vendors its module dependencies)
|
|
18
18
|
- `bunx @zabaca/zbc apply <env>` — apply infrastructure for an environment
|
|
19
|
-
- `bunx @zabaca/zbc destroy <env>` — tear down an
|
|
19
|
+
- `bunx @zabaca/zbc destroy <env>` — tear down every instance in an environment that defines a destroy
|
|
20
20
|
|
|
21
21
|
## Conventions
|
|
22
22
|
|
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
"scripts": {
|
|
7
7
|
"dev": "wrangler dev",
|
|
8
8
|
"deploy": "wrangler deploy",
|
|
9
|
-
"typecheck": "tsc --noEmit"
|
|
9
|
+
"typecheck": "tsc --noEmit",
|
|
10
|
+
"test": "bun test worker"
|
|
10
11
|
},
|
|
11
12
|
"dependencies": {
|
|
12
13
|
"@hono/mcp": "^0.3.1",
|
|
@@ -17,6 +18,7 @@
|
|
|
17
18
|
},
|
|
18
19
|
"devDependencies": {
|
|
19
20
|
"@cloudflare/workers-types": "^4.20250101.0",
|
|
21
|
+
"@types/bun": "^1.3.14",
|
|
20
22
|
"typescript": "^7.0.2",
|
|
21
23
|
"wrangler": "^4.0.0"
|
|
22
24
|
}
|
|
@@ -13,5 +13,7 @@
|
|
|
13
13
|
"lib": ["esnext"],
|
|
14
14
|
"types": ["@cloudflare/workers-types"]
|
|
15
15
|
},
|
|
16
|
-
"include": ["worker"]
|
|
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"]
|
|
17
19
|
}
|
|
@@ -0,0 +1,197 @@
|
|
|
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
|
+
}
|