@zabaca/zbc 0.3.2 → 0.6.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/package.json +5 -4
- package/src/commands/add.ts +145 -67
- package/src/commands/destroy.ts +8 -9
- package/src/commands/init.ts +2 -2
- package/src/engine/destroy.ts +22 -2
- package/src/utils/copy-template.ts +5 -0
- package/templates/CLAUDE.md +1 -1
- package/templates/apps/inbox/package.json +19 -0
- package/templates/apps/inbox/public/index.html +189 -0
- package/templates/apps/inbox/registry.json +9 -0
- package/templates/apps/inbox/tsconfig.json +17 -0
- package/templates/apps/inbox/worker/inbox-do.ts +141 -0
- package/templates/apps/inbox/worker/index.ts +210 -0
- package/templates/apps/inbox/wrangler.jsonc +35 -0
- package/templates/gitignore +2 -1
- package/templates/infra/modules/cloudflare/index.ts +292 -0
- package/templates/infra/modules/cloudflare/registry.json +15 -0
- package/templates/infra/modules/cloudflare-email/index.ts +469 -0
- package/templates/infra/modules/cloudflare-email/registry.json +12 -0
- package/templates/workflows/preview.yml +3 -2
- package/templates/infra/modules/nats-server/index.ts +0 -281
- package/templates/infra/modules/nats-server/registry.json +0 -14
- package/templates/infra/modules/vercel/index.ts +0 -358
- package/templates/infra/modules/vercel/registry.json +0 -15
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { DurableObject } from 'cloudflare:workers'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Inbox — a single SQLite-backed Durable Object holding message metadata and
|
|
5
|
+
* parsed bodies. Raw MIME lives in R2 (DO SQLite caps a value at ~2 MB while
|
|
6
|
+
* a message can be 5 MiB); `r2_key` points at it.
|
|
7
|
+
*
|
|
8
|
+
* One DO instance for the whole inbox (idFromName('inbox')) — transactional
|
|
9
|
+
* ordering beats sharding at this scale.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export interface MessageMeta {
|
|
13
|
+
id: string
|
|
14
|
+
from_addr: string
|
|
15
|
+
to_addr: string
|
|
16
|
+
subject: string
|
|
17
|
+
date: string
|
|
18
|
+
snippet: string
|
|
19
|
+
size: number
|
|
20
|
+
created_at: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface MessageFull extends MessageMeta {
|
|
24
|
+
message_id: string
|
|
25
|
+
text_body: string
|
|
26
|
+
html_body: string
|
|
27
|
+
r2_key: string
|
|
28
|
+
attachments: Array<{ filename: string; mimeType: string; size: number }>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface InsertMessage {
|
|
32
|
+
id: string
|
|
33
|
+
message_id: string
|
|
34
|
+
from_addr: string
|
|
35
|
+
to_addr: string
|
|
36
|
+
subject: string
|
|
37
|
+
date: string
|
|
38
|
+
snippet: string
|
|
39
|
+
text_body: string
|
|
40
|
+
html_body: string
|
|
41
|
+
r2_key: string
|
|
42
|
+
attachments_json: string
|
|
43
|
+
size: number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class Inbox extends DurableObject {
|
|
47
|
+
private sql: SqlStorage
|
|
48
|
+
|
|
49
|
+
constructor(ctx: DurableObjectState, env: unknown) {
|
|
50
|
+
super(ctx, env as never)
|
|
51
|
+
this.sql = ctx.storage.sql
|
|
52
|
+
this.sql.exec(`
|
|
53
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
54
|
+
id TEXT PRIMARY KEY,
|
|
55
|
+
message_id TEXT,
|
|
56
|
+
from_addr TEXT NOT NULL,
|
|
57
|
+
to_addr TEXT NOT NULL,
|
|
58
|
+
subject TEXT,
|
|
59
|
+
date TEXT,
|
|
60
|
+
snippet TEXT,
|
|
61
|
+
text_body TEXT,
|
|
62
|
+
html_body TEXT,
|
|
63
|
+
r2_key TEXT NOT NULL,
|
|
64
|
+
attachments_json TEXT NOT NULL DEFAULT '[]',
|
|
65
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
66
|
+
created_at TEXT NOT NULL
|
|
67
|
+
);
|
|
68
|
+
CREATE INDEX IF NOT EXISTS idx_messages_created ON messages (created_at DESC, id DESC);
|
|
69
|
+
`)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
insert(msg: InsertMessage): void {
|
|
73
|
+
this.sql.exec(
|
|
74
|
+
`INSERT INTO messages
|
|
75
|
+
(id, message_id, from_addr, to_addr, subject, date, snippet,
|
|
76
|
+
text_body, html_body, r2_key, attachments_json, size, created_at)
|
|
77
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
78
|
+
msg.id,
|
|
79
|
+
msg.message_id,
|
|
80
|
+
msg.from_addr,
|
|
81
|
+
msg.to_addr,
|
|
82
|
+
msg.subject,
|
|
83
|
+
msg.date,
|
|
84
|
+
msg.snippet,
|
|
85
|
+
msg.text_body,
|
|
86
|
+
msg.html_body,
|
|
87
|
+
msg.r2_key,
|
|
88
|
+
msg.attachments_json,
|
|
89
|
+
msg.size,
|
|
90
|
+
new Date().toISOString(),
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Newest-first page. `cursor` is the last-seen id (ids are time-ordered). */
|
|
95
|
+
list(limit = 50, cursor?: string): { messages: MessageMeta[]; nextCursor: string | null } {
|
|
96
|
+
const capped = Math.min(Math.max(limit, 1), 200)
|
|
97
|
+
const rows = (cursor
|
|
98
|
+
? this.sql
|
|
99
|
+
.exec(
|
|
100
|
+
`SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
|
|
101
|
+
FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?`,
|
|
102
|
+
cursor,
|
|
103
|
+
capped + 1,
|
|
104
|
+
)
|
|
105
|
+
.toArray()
|
|
106
|
+
: this.sql
|
|
107
|
+
.exec(
|
|
108
|
+
`SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
|
|
109
|
+
FROM messages ORDER BY id DESC LIMIT ?`,
|
|
110
|
+
capped + 1,
|
|
111
|
+
)
|
|
112
|
+
.toArray()) as unknown as MessageMeta[]
|
|
113
|
+
const hasMore = rows.length > capped
|
|
114
|
+
const page = hasMore ? rows.slice(0, capped) : rows
|
|
115
|
+
return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
get(id: string): MessageFull | null {
|
|
119
|
+
const row = this.sql
|
|
120
|
+
.exec(
|
|
121
|
+
`SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
|
|
122
|
+
text_body, html_body, r2_key, attachments_json, size, created_at
|
|
123
|
+
FROM messages WHERE id = ?`,
|
|
124
|
+
id,
|
|
125
|
+
)
|
|
126
|
+
.toArray()[0] as unknown as (MessageFull & { attachments_json: string }) | undefined
|
|
127
|
+
if (!row) return null
|
|
128
|
+
const { attachments_json, ...rest } = row
|
|
129
|
+
return { ...rest, attachments: JSON.parse(attachments_json || '[]') }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Deletes the row; returns the r2_key so the caller can delete the raw blob. */
|
|
133
|
+
delete(id: string): string | null {
|
|
134
|
+
const row = this.sql.exec(`SELECT r2_key FROM messages WHERE id = ?`, id).toArray()[0] as
|
|
135
|
+
| { r2_key: string }
|
|
136
|
+
| undefined
|
|
137
|
+
if (!row) return null
|
|
138
|
+
this.sql.exec(`DELETE FROM messages WHERE id = ?`, id)
|
|
139
|
+
return row.r2_key
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inbox Worker: an agent-accessible inbox for your email domain.
|
|
3
|
+
*
|
|
4
|
+
* - `email()` handler: Email Routing (catch-all) delivers inbound mail here.
|
|
5
|
+
* Raw MIME → R2; parsed metadata + bodies → the Inbox Durable Object.
|
|
6
|
+
* - `/api/*`: bearer-authed JSON API (list / read / raw / delete / send).
|
|
7
|
+
* - Everything else: the static UI in public/ (ASSETS binding).
|
|
8
|
+
*/
|
|
9
|
+
import PostalMime from 'postal-mime'
|
|
10
|
+
import { Inbox } from './inbox-do'
|
|
11
|
+
|
|
12
|
+
export { Inbox }
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Email Service send binding (the NEW object-based API, not the legacy
|
|
16
|
+
* EmailMessage one). The legacy `new EmailMessage(from, to, raw)` path routes
|
|
17
|
+
* through Email Routing and only delivers to VERIFIED destination addresses;
|
|
18
|
+
* the object form goes through Email Sending and accepts any recipient as
|
|
19
|
+
* long as the From domain is onboarded.
|
|
20
|
+
*/
|
|
21
|
+
interface SendEmailBinding {
|
|
22
|
+
send(message: {
|
|
23
|
+
from: string
|
|
24
|
+
to: string
|
|
25
|
+
subject: string
|
|
26
|
+
text?: string
|
|
27
|
+
html?: string
|
|
28
|
+
headers?: Record<string, string>
|
|
29
|
+
}): Promise<unknown>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Env {
|
|
33
|
+
ASSETS: { fetch: (request: Request) => Promise<Response> }
|
|
34
|
+
INBOX: DurableObjectNamespace<Inbox>
|
|
35
|
+
RAW: R2Bucket
|
|
36
|
+
EMAIL: SendEmailBinding
|
|
37
|
+
/** Bearer token guarding /api/* (worker secret, pushed by zbc apply). */
|
|
38
|
+
INBOX_TOKEN?: string
|
|
39
|
+
/** Default From address for /api/send (wrangler var). */
|
|
40
|
+
DEFAULT_FROM?: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Time-ordered id: ms timestamp (base36, padded) + random suffix. Sortable as TEXT. */
|
|
44
|
+
function newId(): string {
|
|
45
|
+
const time = Date.now().toString(36).padStart(9, '0')
|
|
46
|
+
const rand = crypto.getRandomValues(new Uint8Array(8))
|
|
47
|
+
const suffix = Array.from(rand, (b) => b.toString(36).padStart(2, '0'))
|
|
48
|
+
.join('')
|
|
49
|
+
.slice(0, 12)
|
|
50
|
+
return `${time}-${suffix}`
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Constant-time bearer check: compare SHA-256 digests so length never leaks. */
|
|
54
|
+
async function authorized(request: Request, env: Env): Promise<boolean> {
|
|
55
|
+
if (!env.INBOX_TOKEN) return false
|
|
56
|
+
const header = request.headers.get('authorization') ?? ''
|
|
57
|
+
const presented = header.startsWith('Bearer ') ? header.slice(7) : ''
|
|
58
|
+
const enc = new TextEncoder()
|
|
59
|
+
const [a, b] = await Promise.all([
|
|
60
|
+
crypto.subtle.digest('SHA-256', enc.encode(presented)),
|
|
61
|
+
crypto.subtle.digest('SHA-256', enc.encode(env.INBOX_TOKEN)),
|
|
62
|
+
])
|
|
63
|
+
return crypto.subtle.timingSafeEqual(a, b)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function json(data: unknown, status = 200): Response {
|
|
67
|
+
return Response.json(data, { status, headers: { 'cache-control': 'no-store' } })
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function inboxStub(env: Env) {
|
|
71
|
+
return env.INBOX.get(env.INBOX.idFromName('inbox'))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface SendBody {
|
|
75
|
+
to: string
|
|
76
|
+
subject: string
|
|
77
|
+
text?: string
|
|
78
|
+
html?: string
|
|
79
|
+
from?: string
|
|
80
|
+
/** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
|
|
81
|
+
inReplyTo?: string
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export default {
|
|
85
|
+
async email(message: ForwardableEmailMessage, env: Env): Promise<void> {
|
|
86
|
+
const id = newId()
|
|
87
|
+
const r2Key = `msgs/${id}`
|
|
88
|
+
|
|
89
|
+
// Raw MIME first (source of truth), then parse.
|
|
90
|
+
const raw = await new Response(message.raw).arrayBuffer()
|
|
91
|
+
await env.RAW.put(r2Key, raw, {
|
|
92
|
+
customMetadata: { from: message.from, to: message.to },
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
const parsed = await PostalMime.parse(raw)
|
|
96
|
+
const text = parsed.text ?? ''
|
|
97
|
+
const snippet = (text || (parsed.html ?? '').replace(/<[^>]+>/g, ' '))
|
|
98
|
+
.replace(/\s+/g, ' ')
|
|
99
|
+
.trim()
|
|
100
|
+
.slice(0, 200)
|
|
101
|
+
|
|
102
|
+
await inboxStub(env).insert({
|
|
103
|
+
id,
|
|
104
|
+
message_id: parsed.messageId ?? '',
|
|
105
|
+
// Prefer the header From (what the sender shows as) over the SMTP
|
|
106
|
+
// envelope sender (often a bounce address like bounces@cf-bounce.…).
|
|
107
|
+
from_addr: parsed.from?.address ?? message.from,
|
|
108
|
+
to_addr: message.to,
|
|
109
|
+
subject: parsed.subject ?? '',
|
|
110
|
+
date: parsed.date ?? new Date().toISOString(),
|
|
111
|
+
snippet,
|
|
112
|
+
text_body: text,
|
|
113
|
+
html_body: parsed.html ?? '',
|
|
114
|
+
r2_key: r2Key,
|
|
115
|
+
attachments_json: JSON.stringify(
|
|
116
|
+
(parsed.attachments ?? []).map((a) => ({
|
|
117
|
+
filename: a.filename ?? 'attachment',
|
|
118
|
+
mimeType: a.mimeType,
|
|
119
|
+
size: typeof a.content === 'string' ? a.content.length : (a.content?.byteLength ?? 0),
|
|
120
|
+
})),
|
|
121
|
+
),
|
|
122
|
+
size: raw.byteLength,
|
|
123
|
+
})
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
127
|
+
const url = new URL(request.url)
|
|
128
|
+
const { pathname } = url
|
|
129
|
+
|
|
130
|
+
if (!pathname.startsWith('/api/')) {
|
|
131
|
+
return env.ASSETS.fetch(request)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!(await authorized(request, env))) {
|
|
135
|
+
return json({ error: 'unauthorized' }, 401)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const stub = inboxStub(env)
|
|
139
|
+
|
|
140
|
+
// GET /api/messages?limit=&cursor=
|
|
141
|
+
if (pathname === '/api/messages' && request.method === 'GET') {
|
|
142
|
+
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
143
|
+
const cursor = url.searchParams.get('cursor') ?? undefined
|
|
144
|
+
return json(await stub.list(Number.isFinite(limit) ? limit : 50, cursor))
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// POST /api/send
|
|
148
|
+
if (pathname === '/api/send' && request.method === 'POST') {
|
|
149
|
+
let body: SendBody
|
|
150
|
+
try {
|
|
151
|
+
body = (await request.json()) as SendBody
|
|
152
|
+
} catch {
|
|
153
|
+
return json({ error: 'invalid JSON body' }, 400)
|
|
154
|
+
}
|
|
155
|
+
if (!body.to || !body.subject || (!body.text && !body.html)) {
|
|
156
|
+
return json({ error: 'required: to, subject, and text or html' }, 400)
|
|
157
|
+
}
|
|
158
|
+
const from = body.from ?? env.DEFAULT_FROM
|
|
159
|
+
if (!from) return json({ error: 'no from address (set DEFAULT_FROM or pass from)' }, 400)
|
|
160
|
+
|
|
161
|
+
const headers: Record<string, string> | undefined = body.inReplyTo
|
|
162
|
+
? { 'In-Reply-To': body.inReplyTo, References: body.inReplyTo }
|
|
163
|
+
: undefined
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
await env.EMAIL.send({
|
|
167
|
+
from,
|
|
168
|
+
to: body.to,
|
|
169
|
+
subject: body.subject,
|
|
170
|
+
...(body.text ? { text: body.text } : {}),
|
|
171
|
+
...(body.html ? { html: body.html } : {}),
|
|
172
|
+
...(headers ? { headers } : {}),
|
|
173
|
+
})
|
|
174
|
+
} catch (err) {
|
|
175
|
+
return json({ error: `send failed: ${(err as Error).message}` }, 502)
|
|
176
|
+
}
|
|
177
|
+
return json({ ok: true, from, to: body.to })
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// /api/messages/:id[/raw]
|
|
181
|
+
const match = pathname.match(/^\/api\/messages\/([^/]+)(\/raw)?$/)
|
|
182
|
+
if (match) {
|
|
183
|
+
const [, id, rawSuffix] = match
|
|
184
|
+
|
|
185
|
+
if (rawSuffix && request.method === 'GET') {
|
|
186
|
+
const msg = await stub.get(id!)
|
|
187
|
+
if (!msg) return json({ error: 'not found' }, 404)
|
|
188
|
+
const obj = await env.RAW.get(msg.r2_key)
|
|
189
|
+
if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
|
|
190
|
+
return new Response(obj.body, {
|
|
191
|
+
headers: { 'content-type': 'message/rfc822', 'cache-control': 'no-store' },
|
|
192
|
+
})
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (!rawSuffix && request.method === 'GET') {
|
|
196
|
+
const msg = await stub.get(id!)
|
|
197
|
+
return msg ? json(msg) : json({ error: 'not found' }, 404)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (!rawSuffix && request.method === 'DELETE') {
|
|
201
|
+
const r2Key = await stub.delete(id!)
|
|
202
|
+
if (!r2Key) return json({ error: 'not found' }, 404)
|
|
203
|
+
await env.RAW.delete(r2Key)
|
|
204
|
+
return json({ ok: true })
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return json({ error: 'not found' }, 404)
|
|
209
|
+
},
|
|
210
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "node_modules/wrangler/config-schema.json",
|
|
3
|
+
// Agent-accessible inbox. Receives mail via the email() handler (point your
|
|
4
|
+
// Email Routing catch-all at this worker — the cloudflare-email module does
|
|
5
|
+
// that), stores metadata + parsed bodies in a SQLite Durable Object and raw
|
|
6
|
+
// MIME in R2, and exposes a bearer-authed JSON API (list/read/send) plus a
|
|
7
|
+
// minimal static web UI. Outbound mail goes through the send_email binding
|
|
8
|
+
// (Cloudflare Email Sending — the cloudflare-email module onboards the
|
|
9
|
+
// domain).
|
|
10
|
+
"name": "{{PROJECT_NAME}}-inbox",
|
|
11
|
+
"main": "worker/index.ts",
|
|
12
|
+
// Must be recent enough for the Email Service object-form EMAIL.send();
|
|
13
|
+
// older dates fall back to legacy Email Routing semantics (verified
|
|
14
|
+
// destinations only).
|
|
15
|
+
"compatibility_date": "2026-07-01",
|
|
16
|
+
"compatibility_flags": ["nodejs_compat"],
|
|
17
|
+
"observability": { "enabled": true },
|
|
18
|
+
"assets": {
|
|
19
|
+
"directory": "./public",
|
|
20
|
+
"binding": "ASSETS"
|
|
21
|
+
},
|
|
22
|
+
"durable_objects": {
|
|
23
|
+
"bindings": [{ "name": "INBOX", "class_name": "Inbox" }]
|
|
24
|
+
},
|
|
25
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Inbox"] }],
|
|
26
|
+
"r2_buckets": [{ "binding": "RAW", "bucket_name": "{{PROJECT_NAME}}-inbox-raw" }],
|
|
27
|
+
// Unrestricted destination: once your domain is onboarded for Email Sending,
|
|
28
|
+
// the worker may send to arbitrary recipients.
|
|
29
|
+
"send_email": [{ "name": "EMAIL" }],
|
|
30
|
+
"vars": {
|
|
31
|
+
// Default From when /api/send omits one. Must be on your onboarded email
|
|
32
|
+
// domain — EDIT THIS after `zbc add inbox`.
|
|
33
|
+
"DEFAULT_FROM": "inbox@mail.YOUR-DOMAIN.example"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/templates/gitignore
CHANGED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
import * as fs from 'node:fs'
|
|
3
|
+
import { execSync, spawnSync } from 'node:child_process'
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
import { defineModule } from '../../src/define-module'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* cloudflare — deploys a Cloudflare Worker (optionally with static assets, a
|
|
9
|
+
* Durable Object, and a Container) via `wrangler deploy`.
|
|
10
|
+
*
|
|
11
|
+
* This is a THIN orchestrator, the same shape as the turso module: `apply` runs
|
|
12
|
+
* on the operator machine, reads CF creds from `ctx.secrets`, runs an optional
|
|
13
|
+
* local build, then shells `wrangler deploy` in the package's own directory. The
|
|
14
|
+
* Worker TOPOLOGY (name, assets binding, durable_objects, containers,
|
|
15
|
+
* migrations) lives in that package's `wrangler.jsonc` — wrangler is the source
|
|
16
|
+
* of truth for it, not this module. That keeps the module reusable for both
|
|
17
|
+
* plain assets Workers (e.g. a static Astro/Next site) and container-backed
|
|
18
|
+
* payloads (e.g. a DO-bound NATS server).
|
|
19
|
+
*
|
|
20
|
+
* Auth is non-interactive: wrangler reads `CLOUDFLARE_API_TOKEN` +
|
|
21
|
+
* `CLOUDFLARE_ACCOUNT_ID` from the environment, so no `wrangler login` is
|
|
22
|
+
* needed. Worker secrets (e.g. CLAUDE_CODE_OAUTH_TOKEN) are pushed via
|
|
23
|
+
* `wrangler secret put`, piped through stdin so no secret value is ever
|
|
24
|
+
* interpolated into a command string.
|
|
25
|
+
*
|
|
26
|
+
* NOTE on containers (Phase B): `wrangler deploy` builds the container image
|
|
27
|
+
* with Docker, so Docker must be running locally at apply time, and the account
|
|
28
|
+
* must be on a Workers Paid plan with Containers enabled. A plain assets Worker
|
|
29
|
+
* (Phase A) has neither requirement.
|
|
30
|
+
*
|
|
31
|
+
* Two config knobs shape WHICH worker a given apply targets:
|
|
32
|
+
* - `wranglerEnv` selects a named `env.<name>` block in the package's
|
|
33
|
+
* wrangler.jsonc (`--env`), so one package can ship distinct workers per zbc
|
|
34
|
+
* environment from a single config file.
|
|
35
|
+
* - `workerName` renames the deployed worker (`--name`), which is what powers
|
|
36
|
+
* per-PR preview workers (`zbc-<app>-pr-<N>`). The `*.workers.dev` deploy-URL
|
|
37
|
+
* regex still matches a renamed worker's URL.
|
|
38
|
+
*
|
|
39
|
+
* IMPORT SYNC: `workerSecrets` and `workerVars` entries can be either a plain
|
|
40
|
+
* name (resolved from this environment's secrets.yaml, exactly as before) or a
|
|
41
|
+
* `{ name, from, output }` reference into an imported instance's outputs
|
|
42
|
+
* (`ctx.imports[from][output]`, populated by the engine from that instance's
|
|
43
|
+
* validated outputs). Secrets are pushed via `wrangler secret put`, piped
|
|
44
|
+
* through stdin; vars are passed as `wrangler deploy --var KEY:VALUE`. The two
|
|
45
|
+
* are deliberately separate fields — a var is visible in `wrangler.jsonc`/the
|
|
46
|
+
* dashboard, a secret is not — so an imported value's exposure is an explicit
|
|
47
|
+
* per-entry choice, never inferred. Referencing an instance not listed in this
|
|
48
|
+
* instance's `imports`, or an output key that instance doesn't emit, is a hard
|
|
49
|
+
* error naming both.
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/** Resolve the wrangler binary: prefer the package-local one, else `bunx`. */
|
|
53
|
+
function resolveWrangler(workdir: string): { cmd: string; pre: string[] } {
|
|
54
|
+
const local = path.join(workdir, 'node_modules', '.bin', 'wrangler')
|
|
55
|
+
if (fs.existsSync(local)) return { cmd: local, pre: [] }
|
|
56
|
+
// Fall back to bunx on the NODE runtime. Never pass --bun: wrangler under
|
|
57
|
+
// the bun runtime exits 0 after uploading the version but silently skips the
|
|
58
|
+
// deploy/trigger step (2026-07-12 lov incident in Zabaca/ceo: three green
|
|
59
|
+
// applies, zero code deployed).
|
|
60
|
+
return { cmd: 'bunx', pre: ['wrangler'] }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Run wrangler in `workdir` with CF creds in the env; return captured stdout. */
|
|
64
|
+
function wrangler(workdir: string, args: string[], env: NodeJS.ProcessEnv, input?: string): string {
|
|
65
|
+
const { cmd, pre } = resolveWrangler(workdir)
|
|
66
|
+
// spawnSync (not execFileSync) so BOTH streams are captured on success too:
|
|
67
|
+
// wrangler splits its human output across stdout/stderr, and parsing only
|
|
68
|
+
// stdout is how the 2026-07-12 silent-no-deploy went unnoticed.
|
|
69
|
+
const res = spawnSync(cmd, [...pre, ...args], {
|
|
70
|
+
cwd: workdir,
|
|
71
|
+
env,
|
|
72
|
+
input,
|
|
73
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
74
|
+
})
|
|
75
|
+
const combined = `${res.stdout?.toString() ?? ''}\n${res.stderr?.toString() ?? ''}`
|
|
76
|
+
if (res.status !== 0 || res.error) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
`wrangler ${args.join(' ')} failed (exit ${res.status}):\n${combined.trim() || res.error?.message}`,
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
return combined
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const buildSchema = z.object({
|
|
85
|
+
command: z.string(),
|
|
86
|
+
cwd: z.string().optional(),
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A worker secret/var entry: either a plain name (resolved from this
|
|
91
|
+
* environment's secrets.yaml) or a reference into an imported instance's
|
|
92
|
+
* outputs (`ctx.imports[from][output]`).
|
|
93
|
+
*/
|
|
94
|
+
const workerValueSchema = z.union([
|
|
95
|
+
z.string(),
|
|
96
|
+
z.object({
|
|
97
|
+
/** Env var name inside the Worker. */
|
|
98
|
+
name: z.string(),
|
|
99
|
+
/** Instance name — must be listed in this instance's `imports`. */
|
|
100
|
+
from: z.string(),
|
|
101
|
+
/** Which output of that instance to read. */
|
|
102
|
+
output: z.string(),
|
|
103
|
+
}),
|
|
104
|
+
])
|
|
105
|
+
|
|
106
|
+
type WorkerValueEntry = z.infer<typeof workerValueSchema>
|
|
107
|
+
|
|
108
|
+
/** Resolve a workerSecrets/workerVars entry to its `{ name, value }` pair. */
|
|
109
|
+
function resolveWorkerValue(
|
|
110
|
+
entry: WorkerValueEntry,
|
|
111
|
+
ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
|
|
112
|
+
fieldName: string,
|
|
113
|
+
): { name: string; value: string } {
|
|
114
|
+
if (typeof entry === 'string') {
|
|
115
|
+
const value = ctx.secrets[entry]
|
|
116
|
+
if (!value) {
|
|
117
|
+
throw new Error(
|
|
118
|
+
`${fieldName} references "${entry}" but it's missing from this environment's secrets.yaml`,
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
return { name: entry, value }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const instanceOutputs = ctx.imports[entry.from]
|
|
125
|
+
if (instanceOutputs === undefined) {
|
|
126
|
+
throw new Error(
|
|
127
|
+
`${fieldName} entry "${entry.name}" references instance "${entry.from}", which is not in this instance's imports`,
|
|
128
|
+
)
|
|
129
|
+
}
|
|
130
|
+
const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
|
|
131
|
+
if (typeof value !== 'string') {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`${fieldName} entry "${entry.name}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
|
|
134
|
+
)
|
|
135
|
+
}
|
|
136
|
+
return { name: entry.name, value }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export const cloudflareModule = defineModule({
|
|
140
|
+
name: 'cloudflare',
|
|
141
|
+
configSchema: z.object({
|
|
142
|
+
/** Package dir (relative to projectRoot) that holds wrangler.jsonc. */
|
|
143
|
+
workdir: z.string(),
|
|
144
|
+
/**
|
|
145
|
+
* Cloudflare account id. Not a secret (it appears in the dashboard URL), so
|
|
146
|
+
* it lives in config — only the API token is held in secrets.yaml.
|
|
147
|
+
*/
|
|
148
|
+
accountId: z.string(),
|
|
149
|
+
/** Optional local build run before deploy (e.g. `vite build` for assets). */
|
|
150
|
+
build: buildSchema.optional(),
|
|
151
|
+
/**
|
|
152
|
+
* Worker secrets to push after deploy. Each entry is either a plain name
|
|
153
|
+
* — a key in this environment's secrets.yaml, becoming a Worker secret
|
|
154
|
+
* binding of the same name (read at runtime as `env.<NAME>`) — or a
|
|
155
|
+
* `{ name, from, output }` reference into an imported instance's outputs.
|
|
156
|
+
* Pushed via `wrangler secret put` with the value piped through stdin.
|
|
157
|
+
*/
|
|
158
|
+
workerSecrets: z.array(workerValueSchema).default([]),
|
|
159
|
+
/**
|
|
160
|
+
* Worker vars to set at deploy time (`wrangler deploy --var KEY:VALUE`).
|
|
161
|
+
* Same entry shape as `workerSecrets` — plain name (from secrets.yaml) or
|
|
162
|
+
* `{ name, from, output }` — but for non-secret, publicly-visible config.
|
|
163
|
+
* Unlike secrets, var values are passed on the command line, so never
|
|
164
|
+
* route sensitive values through this field.
|
|
165
|
+
*/
|
|
166
|
+
workerVars: z.array(workerValueSchema).default([]),
|
|
167
|
+
/**
|
|
168
|
+
* For container-backed Workers: roll the running container to the new image
|
|
169
|
+
* IMMEDIATELY on deploy (`--containers-rollout immediate`). The wrangler
|
|
170
|
+
* default is a GRADUAL rollout, which never drains a single always-warm,
|
|
171
|
+
* DO-bound container — so a redeployed image silently never takes effect
|
|
172
|
+
* until the container idle-sleeps. Set true whenever the image matters at
|
|
173
|
+
* deploy time. No-op for asset-only Workers.
|
|
174
|
+
*/
|
|
175
|
+
immediateContainerRollout: z.boolean().default(false),
|
|
176
|
+
/**
|
|
177
|
+
* Wrangler named environment (`--env <name>`). When set, deploy and every
|
|
178
|
+
* `secret put` target the matching `env.<name>` block in the package's
|
|
179
|
+
* wrangler.jsonc, so a non-production zbc environment (e.g. `preview`) can
|
|
180
|
+
* ship a DISTINCT worker (own name/domain/bindings) from the same package —
|
|
181
|
+
* without a separate wrangler config. Omit for the top-level (production)
|
|
182
|
+
* worker.
|
|
183
|
+
*/
|
|
184
|
+
wranglerEnv: z.string().optional(),
|
|
185
|
+
/**
|
|
186
|
+
* Override the deployed worker name (`--name <workerName>`). This is what
|
|
187
|
+
* enables per-PR preview workers (e.g. `zbc-landing-pr-42`) from a single
|
|
188
|
+
* wrangler.jsonc: the preview instance sets a PR-scoped name so each PR
|
|
189
|
+
* lands on its own isolated worker + `*.workers.dev` URL. Omit to use the
|
|
190
|
+
* `name` declared in wrangler.jsonc.
|
|
191
|
+
*/
|
|
192
|
+
workerName: z.string().optional(),
|
|
193
|
+
}),
|
|
194
|
+
outputs: z.object({
|
|
195
|
+
deployUrl: z.string(),
|
|
196
|
+
}),
|
|
197
|
+
async apply(config, ctx) {
|
|
198
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
199
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
200
|
+
|
|
201
|
+
const env: NodeJS.ProcessEnv = {
|
|
202
|
+
...process.env,
|
|
203
|
+
CLOUDFLARE_API_TOKEN: apiToken,
|
|
204
|
+
CLOUDFLARE_ACCOUNT_ID: config.accountId,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
208
|
+
|
|
209
|
+
// 1. Optional local build (assets). Inherit stdio so build output streams.
|
|
210
|
+
if (config.build) {
|
|
211
|
+
const buildCwd = path.resolve(ctx.projectRoot, config.build.cwd ?? config.workdir)
|
|
212
|
+
console.log(
|
|
213
|
+
` Building: ${config.build.command} (in ${path.relative(ctx.projectRoot, buildCwd) || '.'})`,
|
|
214
|
+
)
|
|
215
|
+
execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit', env })
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// 2. Resolve every workerVars/workerSecrets entry BEFORE deploy so a bad
|
|
219
|
+
// reference (unknown import, missing output/secret) fails fast, without
|
|
220
|
+
// leaving a deployed-but-unconfigured worker. `resolveWorkerValue` is
|
|
221
|
+
// pure — only the wrangler pushes below have side effects. --var values
|
|
222
|
+
// additionally ship as part of `wrangler deploy` itself (not a follow-up
|
|
223
|
+
// call); secrets are pushed after deploy (step 4) since the script must
|
|
224
|
+
// exist first.
|
|
225
|
+
const resolvedVars = config.workerVars.map((entry) =>
|
|
226
|
+
resolveWorkerValue(entry, ctx, 'workerVars'),
|
|
227
|
+
)
|
|
228
|
+
const resolvedSecrets = config.workerSecrets.map((entry) =>
|
|
229
|
+
resolveWorkerValue(entry, ctx, 'workerSecrets'),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
// 3. Deploy. Creates/updates the Worker script (+ assets, DO, container).
|
|
233
|
+
// --env selects the named wrangler environment (e.g. preview) so it ships
|
|
234
|
+
// a distinct worker from the same package; --name overrides the worker
|
|
235
|
+
// name (per-PR preview workers); both omitted = the package's default.
|
|
236
|
+
const deployArgs = ['deploy']
|
|
237
|
+
if (config.wranglerEnv) deployArgs.push('--env', config.wranglerEnv)
|
|
238
|
+
if (config.workerName) deployArgs.push('--name', config.workerName)
|
|
239
|
+
if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
|
|
240
|
+
for (const { name, value } of resolvedVars) deployArgs.push('--var', `${name}:${value}`)
|
|
241
|
+
console.log(
|
|
242
|
+
` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}`,
|
|
243
|
+
)
|
|
244
|
+
const out = wrangler(workdir, deployArgs, env)
|
|
245
|
+
// Success theater guard: wrangler can exit 0 without actually deploying
|
|
246
|
+
// (the --bun incident above). Require the deploy confirmation line.
|
|
247
|
+
if (!/Deployed\s+\S+\s+triggers/.test(out)) {
|
|
248
|
+
throw new Error(
|
|
249
|
+
`wrangler deploy exited 0 but printed no "Deployed ... triggers" confirmation:\n${out}`,
|
|
250
|
+
)
|
|
251
|
+
}
|
|
252
|
+
const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
|
|
253
|
+
const deployUrl = urlMatch?.[0] ?? ''
|
|
254
|
+
console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
|
|
255
|
+
|
|
256
|
+
// 4. Push Worker secrets (after deploy: the script must exist first).
|
|
257
|
+
// Already resolved in step 2, so a misconfigured reference never reaches
|
|
258
|
+
// this point. Value piped via stdin so it never lands in a command
|
|
259
|
+
// string or the log.
|
|
260
|
+
for (const { name, value } of resolvedSecrets) {
|
|
261
|
+
const secretArgs = ['secret', 'put', name]
|
|
262
|
+
if (config.wranglerEnv) secretArgs.push('--env', config.wranglerEnv)
|
|
263
|
+
if (config.workerName) secretArgs.push('--name', config.workerName)
|
|
264
|
+
wrangler(workdir, secretArgs, env, value)
|
|
265
|
+
console.log(` Set Worker secret: ${name}`)
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return { deployUrl }
|
|
269
|
+
},
|
|
270
|
+
async destroy(config, ctx) {
|
|
271
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
272
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
273
|
+
const env: NodeJS.ProcessEnv = {
|
|
274
|
+
...process.env,
|
|
275
|
+
CLOUDFLARE_API_TOKEN: apiToken,
|
|
276
|
+
CLOUDFLARE_ACCOUNT_ID: config.accountId,
|
|
277
|
+
}
|
|
278
|
+
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
279
|
+
// `wrangler delete` removes the Worker (and its DO/container). Non-fatal if
|
|
280
|
+
// already gone. --env / --name target the same worker `apply` deployed
|
|
281
|
+
// (named environment and/or per-PR preview name).
|
|
282
|
+
try {
|
|
283
|
+
const deleteArgs = ['delete', '--force']
|
|
284
|
+
if (config.wranglerEnv) deleteArgs.push('--env', config.wranglerEnv)
|
|
285
|
+
if (config.workerName) deleteArgs.push('--name', config.workerName)
|
|
286
|
+
wrangler(workdir, deleteArgs, env)
|
|
287
|
+
console.log(' Deleted Worker')
|
|
288
|
+
} catch (err) {
|
|
289
|
+
console.log(` Worker delete skipped: ${(err as Error).message}`)
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
})
|