@zabaca/zbc 0.4.0 → 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 +143 -67
- package/src/commands/init.ts +2 -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 +172 -43
- package/templates/infra/modules/cloudflare/registry.json +1 -1
- 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 -267
- package/templates/infra/modules/nats-server/registry.json +0 -12
- package/templates/infra/modules/vercel/index.ts +0 -358
- package/templates/infra/modules/vercel/registry.json +0 -15
|
@@ -1,267 +0,0 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto'
|
|
2
|
-
import { z } from 'zod'
|
|
3
|
-
import { defineModule } from '../../src/define-module'
|
|
4
|
-
|
|
5
|
-
const FLY_API = 'https://api.machines.dev'
|
|
6
|
-
const FLY_GRAPHQL = 'https://api.fly.io/graphql'
|
|
7
|
-
const NATS_USER = 'app'
|
|
8
|
-
const MACHINE_TAG = { 'managed-by': 'zbc', instance: 'nats' } as const
|
|
9
|
-
|
|
10
|
-
interface FlyApp {
|
|
11
|
-
id: string
|
|
12
|
-
name: string
|
|
13
|
-
organization: { slug: string }
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
interface FlyMachine {
|
|
17
|
-
id: string
|
|
18
|
-
name: string
|
|
19
|
-
state: string
|
|
20
|
-
config?: {
|
|
21
|
-
metadata?: Record<string, string>
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
async function flyFetch<T = unknown>(
|
|
26
|
-
path: string,
|
|
27
|
-
token: string,
|
|
28
|
-
options?: RequestInit,
|
|
29
|
-
): Promise<T | null> {
|
|
30
|
-
const res = await fetch(`${FLY_API}${path}`, {
|
|
31
|
-
...options,
|
|
32
|
-
headers: {
|
|
33
|
-
Authorization: `Bearer ${token}`,
|
|
34
|
-
'Content-Type': 'application/json',
|
|
35
|
-
...options?.headers,
|
|
36
|
-
},
|
|
37
|
-
})
|
|
38
|
-
|
|
39
|
-
if (res.status === 404) return null
|
|
40
|
-
if (!res.ok) {
|
|
41
|
-
const body = await res.text()
|
|
42
|
-
throw new Error(`Fly API ${path} failed (${res.status}): ${body}`)
|
|
43
|
-
}
|
|
44
|
-
if (res.status === 204) return null
|
|
45
|
-
return (await res.json()) as T
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
async function flyGraphQL<T>(
|
|
49
|
-
token: string,
|
|
50
|
-
query: string,
|
|
51
|
-
variables: Record<string, unknown>,
|
|
52
|
-
): Promise<T> {
|
|
53
|
-
const res = await fetch(FLY_GRAPHQL, {
|
|
54
|
-
method: 'POST',
|
|
55
|
-
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
56
|
-
body: JSON.stringify({ query, variables }),
|
|
57
|
-
})
|
|
58
|
-
const body = (await res.json()) as { data?: T; errors?: Array<{ message: string }> }
|
|
59
|
-
if (body.errors?.length) {
|
|
60
|
-
throw new Error(`Fly GraphQL: ${body.errors.map((e) => e.message).join('; ')}`)
|
|
61
|
-
}
|
|
62
|
-
if (!body.data) throw new Error('Fly GraphQL: empty response')
|
|
63
|
-
return body.data
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Fly's Machines REST API does not auto-allocate public IPs. Without this,
|
|
68
|
-
* <app>.fly.dev never resolves. IP allocation isn't on the Machines API yet
|
|
69
|
-
* — we go through GraphQL. shared_v4 is org-wide and not listed per-app,
|
|
70
|
-
* so we always (re-)issue the mutation; it's idempotent. v6 is per-app, so
|
|
71
|
-
* we only allocate if not present.
|
|
72
|
-
*/
|
|
73
|
-
async function ensureIPs(appName: string, token: string): Promise<void> {
|
|
74
|
-
const list = await flyGraphQL<{ app: { ipAddresses: { nodes: Array<{ type: string }> } } }>(
|
|
75
|
-
token,
|
|
76
|
-
`query($name: String!) { app(name: $name) { ipAddresses { nodes { type } } } }`,
|
|
77
|
-
{ name: appName },
|
|
78
|
-
)
|
|
79
|
-
const hasV6 = list.app.ipAddresses.nodes.some((n) => n.type === 'v6')
|
|
80
|
-
|
|
81
|
-
await flyGraphQL(
|
|
82
|
-
token,
|
|
83
|
-
`mutation($appId: ID!) { allocateIpAddress(input: {appId: $appId, type: shared_v4}) { ipAddress { address } } }`,
|
|
84
|
-
{ appId: appName },
|
|
85
|
-
)
|
|
86
|
-
if (!hasV6) {
|
|
87
|
-
await flyGraphQL(
|
|
88
|
-
token,
|
|
89
|
-
`mutation($appId: ID!) { allocateIpAddress(input: {appId: $appId, type: v6}) { ipAddress { address } } }`,
|
|
90
|
-
{ appId: appName },
|
|
91
|
-
)
|
|
92
|
-
console.log(` Allocated IPv6 for "${appName}"`)
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function renderConf(): string {
|
|
97
|
-
return `# Managed by zbc — do not edit by hand.
|
|
98
|
-
|
|
99
|
-
http_port: 8222
|
|
100
|
-
|
|
101
|
-
websocket {
|
|
102
|
-
port: 8080
|
|
103
|
-
no_tls: true
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
authorization {
|
|
107
|
-
user: ${NATS_USER}
|
|
108
|
-
password: $NATS_PASSWORD
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
max_payload: 1MB
|
|
112
|
-
write_deadline: "10s"
|
|
113
|
-
`
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function isManaged(machine: FlyMachine): boolean {
|
|
117
|
-
const md = machine.config?.metadata ?? {}
|
|
118
|
-
return md['managed-by'] === MACHINE_TAG['managed-by'] && md.instance === MACHINE_TAG.instance
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export const natsServerModule = defineModule({
|
|
122
|
-
name: 'nats-server',
|
|
123
|
-
configSchema: z.object({
|
|
124
|
-
appName: z.string(),
|
|
125
|
-
flyOrg: z.string().default('personal'),
|
|
126
|
-
region: z.string().default('iad'),
|
|
127
|
-
memoryMB: z.number().default(256),
|
|
128
|
-
cpuKind: z.enum(['shared', 'performance']).default('shared'),
|
|
129
|
-
cpus: z.number().default(1),
|
|
130
|
-
}),
|
|
131
|
-
outputs: z.object({
|
|
132
|
-
url: z.string(),
|
|
133
|
-
user: z.string(),
|
|
134
|
-
password: z.string(),
|
|
135
|
-
}),
|
|
136
|
-
async apply(config, ctx) {
|
|
137
|
-
const flyToken = ctx.secrets['FLY_API_TOKEN']
|
|
138
|
-
if (!flyToken) throw new Error('Missing secret: FLY_API_TOKEN')
|
|
139
|
-
|
|
140
|
-
const password = ctx.secrets['NATS_PASSWORD']
|
|
141
|
-
if (!password) {
|
|
142
|
-
const generated = randomBytes(32).toString('hex')
|
|
143
|
-
throw new Error(
|
|
144
|
-
`Missing secret: NATS_PASSWORD\n` +
|
|
145
|
-
` Generated one for you — add to your environment's secrets.yaml and re-run:\n\n` +
|
|
146
|
-
` NATS_PASSWORD: ${generated}\n`,
|
|
147
|
-
)
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
let app = await flyFetch<FlyApp>(`/v1/apps/${config.appName}`, flyToken)
|
|
151
|
-
if (app) {
|
|
152
|
-
console.log(` Fly app "${config.appName}" already exists`)
|
|
153
|
-
} else {
|
|
154
|
-
app = await flyFetch<FlyApp>('/v1/apps', flyToken, {
|
|
155
|
-
method: 'POST',
|
|
156
|
-
body: JSON.stringify({ app_name: config.appName, org_slug: config.flyOrg }),
|
|
157
|
-
})
|
|
158
|
-
console.log(` Created Fly app "${config.appName}" in org "${config.flyOrg}"`)
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
await ensureIPs(config.appName, flyToken)
|
|
162
|
-
|
|
163
|
-
const machineConfig = {
|
|
164
|
-
image: 'nats:latest',
|
|
165
|
-
env: { NATS_PASSWORD: password },
|
|
166
|
-
files: [
|
|
167
|
-
{
|
|
168
|
-
guest_path: '/etc/nats/nats-server.conf',
|
|
169
|
-
raw_value: Buffer.from(renderConf(), 'utf8').toString('base64'),
|
|
170
|
-
},
|
|
171
|
-
],
|
|
172
|
-
init: { cmd: ['-c', '/etc/nats/nats-server.conf'] },
|
|
173
|
-
services: [
|
|
174
|
-
{
|
|
175
|
-
protocol: 'tcp',
|
|
176
|
-
internal_port: 8080,
|
|
177
|
-
ports: [{ port: 443, handlers: ['tls', 'http'] }],
|
|
178
|
-
},
|
|
179
|
-
],
|
|
180
|
-
checks: {
|
|
181
|
-
healthz: {
|
|
182
|
-
type: 'http',
|
|
183
|
-
port: 8222,
|
|
184
|
-
path: '/healthz',
|
|
185
|
-
interval: '15s',
|
|
186
|
-
timeout: '5s',
|
|
187
|
-
grace_period: '10s',
|
|
188
|
-
},
|
|
189
|
-
},
|
|
190
|
-
metadata: { ...MACHINE_TAG },
|
|
191
|
-
guest: {
|
|
192
|
-
cpu_kind: config.cpuKind,
|
|
193
|
-
cpus: config.cpus,
|
|
194
|
-
memory_mb: config.memoryMB,
|
|
195
|
-
},
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
const machines =
|
|
199
|
-
(await flyFetch<FlyMachine[]>(`/v1/apps/${config.appName}/machines`, flyToken)) ?? []
|
|
200
|
-
const managed = machines.filter(isManaged)
|
|
201
|
-
|
|
202
|
-
let machineId: string
|
|
203
|
-
if (managed.length === 0) {
|
|
204
|
-
const created = await flyFetch<FlyMachine>(`/v1/apps/${config.appName}/machines`, flyToken, {
|
|
205
|
-
method: 'POST',
|
|
206
|
-
body: JSON.stringify({
|
|
207
|
-
name: 'nats',
|
|
208
|
-
region: config.region,
|
|
209
|
-
config: machineConfig,
|
|
210
|
-
}),
|
|
211
|
-
})
|
|
212
|
-
if (!created) throw new Error('Fly machine create returned no body')
|
|
213
|
-
machineId = created.id
|
|
214
|
-
console.log(` Created machine "${created.id}" in ${config.region}`)
|
|
215
|
-
} else {
|
|
216
|
-
machineId = managed[0].id
|
|
217
|
-
await flyFetch<FlyMachine>(`/v1/apps/${config.appName}/machines/${machineId}`, flyToken, {
|
|
218
|
-
method: 'POST',
|
|
219
|
-
body: JSON.stringify({ config: machineConfig, region: config.region }),
|
|
220
|
-
})
|
|
221
|
-
console.log(` Updated machine "${machineId}"`)
|
|
222
|
-
if (managed.length > 1) {
|
|
223
|
-
console.warn(
|
|
224
|
-
` ⚠ Found ${managed.length} machines tagged managed-by=zbc; updated first, ignored the rest`,
|
|
225
|
-
)
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
// Fly's update cycle (stop → swap config → start) auto-starts the
|
|
230
|
-
// machine, but the full cycle can take 60–90s. Don't call /start
|
|
231
|
-
// ourselves — it races the auto-start and 412s with "getting replaced".
|
|
232
|
-
// /wait caps at 60s server-side; poll up to ~4 minutes.
|
|
233
|
-
const waitURL = `/v1/apps/${config.appName}/machines/${machineId}/wait?state=started&timeout=60`
|
|
234
|
-
let started = false
|
|
235
|
-
for (let attempt = 0; attempt < 4; attempt++) {
|
|
236
|
-
try {
|
|
237
|
-
await flyFetch(waitURL, flyToken)
|
|
238
|
-
started = true
|
|
239
|
-
break
|
|
240
|
-
} catch (err) {
|
|
241
|
-
const msg = err instanceof Error ? err.message : String(err)
|
|
242
|
-
if (!msg.includes('(408)')) throw err
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
if (!started) throw new Error(`Machine "${machineId}" did not reach started state in 4m`)
|
|
246
|
-
console.log(` Machine "${machineId}" started`)
|
|
247
|
-
|
|
248
|
-
return {
|
|
249
|
-
url: `wss://${config.appName}.fly.dev`,
|
|
250
|
-
user: NATS_USER,
|
|
251
|
-
password,
|
|
252
|
-
}
|
|
253
|
-
},
|
|
254
|
-
async destroy(config, ctx) {
|
|
255
|
-
const flyToken = ctx.secrets['FLY_API_TOKEN']
|
|
256
|
-
if (!flyToken) throw new Error('Missing secret: FLY_API_TOKEN')
|
|
257
|
-
|
|
258
|
-
const result = await flyFetch(`/v1/apps/${config.appName}?force=true`, flyToken, {
|
|
259
|
-
method: 'DELETE',
|
|
260
|
-
})
|
|
261
|
-
if (result === null) {
|
|
262
|
-
console.log(` Fly app "${config.appName}" deleted (or did not exist)`)
|
|
263
|
-
} else {
|
|
264
|
-
console.log(` Fly app "${config.appName}" deleted`)
|
|
265
|
-
}
|
|
266
|
-
},
|
|
267
|
-
})
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "nats-server",
|
|
3
|
-
"description": "Self-hosted NATS pub/sub server on Fly.io (WebSocket, single shared cred)",
|
|
4
|
-
"files": [{ "path": "index.ts" }],
|
|
5
|
-
"dependencies": {
|
|
6
|
-
"zod": "^3.24.0"
|
|
7
|
-
},
|
|
8
|
-
"secrets": ["FLY_API_TOKEN", "NATS_PASSWORD"],
|
|
9
|
-
"signupUrl": "https://fly.io/app/sign-up",
|
|
10
|
-
"tokenUrl": "https://fly.io/user/personal_access_tokens",
|
|
11
|
-
"instructions": "Add FLY_API_TOKEN and NATS_PASSWORD to packages/infra/environments/<env>/secrets.yaml. If you don't have a NATS_PASSWORD yet, run apply once and the module will print a generated value to paste in. The module creates a single Fly Machine running nats:latest with WebSocket on wss://<appName>.fly.dev."
|
|
12
|
-
}
|
|
@@ -1,358 +0,0 @@
|
|
|
1
|
-
import * as path from 'node:path'
|
|
2
|
-
import * as fs from 'node:fs'
|
|
3
|
-
import { execSync } from 'node:child_process'
|
|
4
|
-
import { z } from 'zod'
|
|
5
|
-
import { defineModule } from '../../src/define-module'
|
|
6
|
-
|
|
7
|
-
const VERCEL_API = 'https://api.vercel.com'
|
|
8
|
-
|
|
9
|
-
interface VercelProject {
|
|
10
|
-
id: string
|
|
11
|
-
name: string
|
|
12
|
-
framework?: string | null
|
|
13
|
-
accountId: string
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
interface VercelEnvVar {
|
|
17
|
-
id: string
|
|
18
|
-
key: string
|
|
19
|
-
value: string
|
|
20
|
-
target: string[]
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function withTeam(p: string, teamId?: string) {
|
|
24
|
-
if (!teamId) return p
|
|
25
|
-
const sep = p.includes('?') ? '&' : '?'
|
|
26
|
-
return `${p}${sep}teamId=${teamId}`
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
async function vercelFetch(p: string, token: string, teamId?: string, options?: RequestInit) {
|
|
30
|
-
const res = await fetch(`${VERCEL_API}${withTeam(p, teamId)}`, {
|
|
31
|
-
...options,
|
|
32
|
-
headers: {
|
|
33
|
-
Authorization: `Bearer ${token}`,
|
|
34
|
-
'Content-Type': 'application/json',
|
|
35
|
-
...options?.headers,
|
|
36
|
-
},
|
|
37
|
-
})
|
|
38
|
-
|
|
39
|
-
if (!res.ok) {
|
|
40
|
-
const body = await res.text()
|
|
41
|
-
throw new Error(`Vercel API ${p} failed (${res.status}): ${body}`)
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
if (res.status === 204) return null
|
|
45
|
-
return res.json()
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
async function findProject(
|
|
49
|
-
token: string,
|
|
50
|
-
projectName: string,
|
|
51
|
-
teamId?: string,
|
|
52
|
-
): Promise<VercelProject | null> {
|
|
53
|
-
try {
|
|
54
|
-
return await vercelFetch(`/v9/projects/${projectName}`, token, teamId)
|
|
55
|
-
} catch {
|
|
56
|
-
return null
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
interface CreateProjectInput {
|
|
61
|
-
framework?: string | null
|
|
62
|
-
rootDirectory?: string
|
|
63
|
-
installCommand?: string
|
|
64
|
-
buildCommand?: string
|
|
65
|
-
outputDirectory?: string
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
async function createProject(
|
|
69
|
-
token: string,
|
|
70
|
-
projectName: string,
|
|
71
|
-
teamId: string | undefined,
|
|
72
|
-
input: CreateProjectInput,
|
|
73
|
-
): Promise<VercelProject> {
|
|
74
|
-
const body: Record<string, unknown> = { name: projectName }
|
|
75
|
-
if (input.framework !== undefined) body.framework = input.framework
|
|
76
|
-
if (input.rootDirectory !== undefined) body.rootDirectory = input.rootDirectory
|
|
77
|
-
if (input.installCommand !== undefined) body.installCommand = input.installCommand
|
|
78
|
-
if (input.buildCommand !== undefined) body.buildCommand = input.buildCommand
|
|
79
|
-
if (input.outputDirectory !== undefined) body.outputDirectory = input.outputDirectory
|
|
80
|
-
|
|
81
|
-
return vercelFetch('/v10/projects', token, teamId, {
|
|
82
|
-
method: 'POST',
|
|
83
|
-
body: JSON.stringify(body),
|
|
84
|
-
})
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* PATCH project settings on every apply so config-as-code stays
|
|
89
|
-
* authoritative. createProject only sets these on first creation; without
|
|
90
|
-
* this call, edits to rootDirectory/installCommand/etc. are silently
|
|
91
|
-
* ignored on existing projects.
|
|
92
|
-
*/
|
|
93
|
-
async function syncProjectSettings(
|
|
94
|
-
token: string,
|
|
95
|
-
projectId: string,
|
|
96
|
-
teamId: string | undefined,
|
|
97
|
-
input: CreateProjectInput,
|
|
98
|
-
) {
|
|
99
|
-
const body: Record<string, unknown> = {}
|
|
100
|
-
// Only set fields the caller explicitly provided. Vercel treats `null`
|
|
101
|
-
// as "use default", which we want for framework when caller didn't pass.
|
|
102
|
-
if (input.framework !== undefined) body.framework = input.framework
|
|
103
|
-
if (input.rootDirectory !== undefined) body.rootDirectory = input.rootDirectory
|
|
104
|
-
if (input.installCommand !== undefined) body.installCommand = input.installCommand
|
|
105
|
-
if (input.buildCommand !== undefined) body.buildCommand = input.buildCommand
|
|
106
|
-
if (input.outputDirectory !== undefined) body.outputDirectory = input.outputDirectory
|
|
107
|
-
|
|
108
|
-
if (Object.keys(body).length === 0) return
|
|
109
|
-
|
|
110
|
-
await vercelFetch(`/v9/projects/${projectId}`, token, teamId, {
|
|
111
|
-
method: 'PATCH',
|
|
112
|
-
body: JSON.stringify(body),
|
|
113
|
-
})
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async function syncEnvVars(
|
|
117
|
-
token: string,
|
|
118
|
-
projectId: string,
|
|
119
|
-
teamId: string | undefined,
|
|
120
|
-
desired: Record<string, string>,
|
|
121
|
-
target: string[],
|
|
122
|
-
) {
|
|
123
|
-
const data = (await vercelFetch(`/v9/projects/${projectId}/env`, token, teamId)) as {
|
|
124
|
-
envs: VercelEnvVar[]
|
|
125
|
-
}
|
|
126
|
-
const existing = data.envs ?? []
|
|
127
|
-
|
|
128
|
-
for (const [key, value] of Object.entries(desired)) {
|
|
129
|
-
const found = existing.find((e) => e.key === key)
|
|
130
|
-
if (found) {
|
|
131
|
-
await vercelFetch(`/v9/projects/${projectId}/env/${found.id}`, token, teamId, {
|
|
132
|
-
method: 'PATCH',
|
|
133
|
-
body: JSON.stringify({ value, target }),
|
|
134
|
-
})
|
|
135
|
-
} else {
|
|
136
|
-
await vercelFetch(`/v9/projects/${projectId}/env`, token, teamId, {
|
|
137
|
-
method: 'POST',
|
|
138
|
-
body: JSON.stringify({ key, value, target, type: 'encrypted' }),
|
|
139
|
-
})
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
async function syncDomain(
|
|
145
|
-
token: string,
|
|
146
|
-
projectId: string,
|
|
147
|
-
teamId: string | undefined,
|
|
148
|
-
domain: string,
|
|
149
|
-
) {
|
|
150
|
-
try {
|
|
151
|
-
await vercelFetch(`/v10/projects/${projectId}/domains`, token, teamId, {
|
|
152
|
-
method: 'POST',
|
|
153
|
-
body: JSON.stringify({ name: domain }),
|
|
154
|
-
})
|
|
155
|
-
} catch {
|
|
156
|
-
// Domain may already be configured — fine.
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function findVercelBin(projectRoot: string): string {
|
|
161
|
-
const candidates = [
|
|
162
|
-
path.join(projectRoot, 'packages/cli/node_modules/.bin/vercel'),
|
|
163
|
-
path.join(projectRoot, 'node_modules/.bin/vercel'),
|
|
164
|
-
]
|
|
165
|
-
for (const c of candidates) {
|
|
166
|
-
if (fs.existsSync(c)) return c
|
|
167
|
-
}
|
|
168
|
-
throw new Error('vercel CLI not found. Install it: bun add -d vercel in packages/cli')
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
function deployToVercel(
|
|
172
|
-
token: string,
|
|
173
|
-
uploadDir: string,
|
|
174
|
-
teamId: string | undefined,
|
|
175
|
-
production: boolean,
|
|
176
|
-
projectRoot: string,
|
|
177
|
-
) {
|
|
178
|
-
const vercelBin = findVercelBin(projectRoot)
|
|
179
|
-
const args = [vercelBin, 'deploy', uploadDir, '--token', token, '--yes']
|
|
180
|
-
if (teamId) args.push('--scope', teamId)
|
|
181
|
-
if (production) args.push('--prod')
|
|
182
|
-
|
|
183
|
-
console.log(
|
|
184
|
-
` Deploying ${path.relative(projectRoot, uploadDir) || '.'}${production ? ' (production)' : ''}...`,
|
|
185
|
-
)
|
|
186
|
-
|
|
187
|
-
try {
|
|
188
|
-
const output = execSync(args.join(' '), { stdio: ['ignore', 'pipe', 'pipe'] })
|
|
189
|
-
const raw = output.toString().trim()
|
|
190
|
-
const urlMatch = raw.match(/https:\/\/[^\s"',}]+/)
|
|
191
|
-
const deployUrl = urlMatch?.[0] ?? ''
|
|
192
|
-
console.log(` Deployed: ${deployUrl}`)
|
|
193
|
-
return deployUrl
|
|
194
|
-
} catch (err: unknown) {
|
|
195
|
-
const stderr = (err as { stderr?: Buffer }).stderr?.toString() ?? ''
|
|
196
|
-
throw new Error(`Vercel deploy failed: ${stderr}`)
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
const buildModeSchema = z.object({
|
|
201
|
-
command: z.string(),
|
|
202
|
-
cwd: z.string().optional(),
|
|
203
|
-
outputDir: z.string(),
|
|
204
|
-
})
|
|
205
|
-
|
|
206
|
-
export const vercelModule = defineModule({
|
|
207
|
-
name: 'vercel',
|
|
208
|
-
configSchema: z
|
|
209
|
-
.object({
|
|
210
|
-
projectName: z.string(),
|
|
211
|
-
teamId: z.string().optional(),
|
|
212
|
-
domain: z.string().optional(),
|
|
213
|
-
framework: z.string().nullable().optional(),
|
|
214
|
-
|
|
215
|
-
// Mode A — module builds locally, uploads outputDir as static.
|
|
216
|
-
build: buildModeSchema.optional(),
|
|
217
|
-
|
|
218
|
-
// Mode B — Vercel builds from the uploaded sourceDir.
|
|
219
|
-
sourceDir: z.string().optional(),
|
|
220
|
-
rootDirectory: z.string().optional(),
|
|
221
|
-
installCommand: z.string().optional(),
|
|
222
|
-
buildCommand: z.string().optional(),
|
|
223
|
-
outputDirectory: z.string().optional(),
|
|
224
|
-
|
|
225
|
-
production: z.boolean().default(true),
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Secrets to forward to the Vercel project as runtime env vars.
|
|
229
|
-
* Each entry names a key in the environment's secrets.yaml; the same
|
|
230
|
-
* name is set on the Vercel project. Used for app-runtime secrets
|
|
231
|
-
* that aren't outputs of an imported instance (e.g. BETTER_AUTH_SECRET).
|
|
232
|
-
*/
|
|
233
|
-
secretEnv: z.array(z.string()).default([]),
|
|
234
|
-
})
|
|
235
|
-
.refine((c) => Boolean(c.build) !== Boolean(c.sourceDir), {
|
|
236
|
-
message: 'Provide exactly one of `build` (static prebuilt) or `sourceDir` (Vercel builds).',
|
|
237
|
-
}),
|
|
238
|
-
outputs: z.object({
|
|
239
|
-
projectUrl: z.string(),
|
|
240
|
-
projectId: z.string(),
|
|
241
|
-
deployUrl: z.string().optional(),
|
|
242
|
-
}),
|
|
243
|
-
async apply(config, ctx) {
|
|
244
|
-
const vercelToken = ctx.secrets['VERCEL_TOKEN']
|
|
245
|
-
if (!vercelToken) throw new Error('Missing secret: VERCEL_TOKEN')
|
|
246
|
-
|
|
247
|
-
const isStatic = Boolean(config.build)
|
|
248
|
-
|
|
249
|
-
const settingsInput: CreateProjectInput = isStatic
|
|
250
|
-
? { framework: null }
|
|
251
|
-
: {
|
|
252
|
-
framework: config.framework ?? undefined,
|
|
253
|
-
rootDirectory: config.rootDirectory,
|
|
254
|
-
installCommand: config.installCommand,
|
|
255
|
-
buildCommand: config.buildCommand,
|
|
256
|
-
outputDirectory: config.outputDirectory,
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
let project = await findProject(vercelToken, config.projectName, config.teamId)
|
|
260
|
-
if (project) {
|
|
261
|
-
console.log(` Project "${config.projectName}" already exists`)
|
|
262
|
-
await syncProjectSettings(vercelToken, project.id, config.teamId, settingsInput)
|
|
263
|
-
console.log(` Synced project settings`)
|
|
264
|
-
} else {
|
|
265
|
-
project = await createProject(vercelToken, config.projectName, config.teamId, settingsInput)
|
|
266
|
-
console.log(` Created project "${config.projectName}"`)
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
const envVars: Record<string, string> = {}
|
|
270
|
-
for (const [instanceName, outputs] of Object.entries(ctx.imports)) {
|
|
271
|
-
if (typeof outputs === 'object' && outputs !== null) {
|
|
272
|
-
for (const [key, value] of Object.entries(outputs as Record<string, unknown>)) {
|
|
273
|
-
if (typeof value === 'string') {
|
|
274
|
-
const envKey = `${instanceName}_${key}`.toUpperCase().replace(/-/g, '_')
|
|
275
|
-
envVars[envKey] = value
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
// Vercel doesn't expose the project slug as a system env var. Inject it
|
|
281
|
-
// ourselves so runtime code can construct the bare `<projectName>.vercel.app`
|
|
282
|
-
// alias (which VERCEL_PROJECT_PRODUCTION_URL hides once a custom domain
|
|
283
|
-
// is attached).
|
|
284
|
-
envVars['VERCEL_PROJECT_NAME'] = config.projectName
|
|
285
|
-
for (const secretName of config.secretEnv) {
|
|
286
|
-
const value = ctx.secrets[secretName]
|
|
287
|
-
if (!value) {
|
|
288
|
-
throw new Error(
|
|
289
|
-
`secretEnv references "${secretName}" but it's missing from this environment's secrets.yaml`,
|
|
290
|
-
)
|
|
291
|
-
}
|
|
292
|
-
envVars[secretName] = value
|
|
293
|
-
}
|
|
294
|
-
if (Object.keys(envVars).length > 0) {
|
|
295
|
-
await syncEnvVars(vercelToken, project.id, config.teamId, envVars, [
|
|
296
|
-
'production',
|
|
297
|
-
'preview',
|
|
298
|
-
'development',
|
|
299
|
-
])
|
|
300
|
-
console.log(` Synced env vars: ${Object.keys(envVars).join(', ')}`)
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
if (config.domain) {
|
|
304
|
-
await syncDomain(vercelToken, project.id, config.teamId, config.domain)
|
|
305
|
-
console.log(` Domain "${config.domain}" configured`)
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
let uploadDir: string
|
|
309
|
-
if (isStatic && config.build) {
|
|
310
|
-
const buildCwd = path.resolve(ctx.projectRoot, config.build.cwd ?? '.')
|
|
311
|
-
console.log(
|
|
312
|
-
` Building: ${config.build.command} (in ${path.relative(ctx.projectRoot, buildCwd) || '.'})`,
|
|
313
|
-
)
|
|
314
|
-
execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit' })
|
|
315
|
-
uploadDir = path.resolve(ctx.projectRoot, config.build.outputDir)
|
|
316
|
-
} else if (config.sourceDir) {
|
|
317
|
-
uploadDir = path.resolve(ctx.projectRoot, config.sourceDir)
|
|
318
|
-
} else {
|
|
319
|
-
// refine() guarantees this, but TS doesn't know it
|
|
320
|
-
throw new Error('unreachable: neither build nor sourceDir set')
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
const vercelDir = path.join(uploadDir, '.vercel')
|
|
324
|
-
fs.mkdirSync(vercelDir, { recursive: true })
|
|
325
|
-
fs.writeFileSync(
|
|
326
|
-
path.join(vercelDir, 'project.json'),
|
|
327
|
-
JSON.stringify({ orgId: project.accountId, projectId: project.id }),
|
|
328
|
-
)
|
|
329
|
-
|
|
330
|
-
const deployUrl = deployToVercel(
|
|
331
|
-
vercelToken,
|
|
332
|
-
uploadDir,
|
|
333
|
-
config.teamId,
|
|
334
|
-
config.production,
|
|
335
|
-
ctx.projectRoot,
|
|
336
|
-
)
|
|
337
|
-
|
|
338
|
-
return {
|
|
339
|
-
projectUrl: `https://${config.projectName}.vercel.app`,
|
|
340
|
-
projectId: project.id,
|
|
341
|
-
deployUrl,
|
|
342
|
-
}
|
|
343
|
-
},
|
|
344
|
-
async destroy(config, ctx) {
|
|
345
|
-
const vercelToken = ctx.secrets['VERCEL_TOKEN']
|
|
346
|
-
if (!vercelToken) throw new Error('Missing secret: VERCEL_TOKEN')
|
|
347
|
-
|
|
348
|
-
const project = await findProject(vercelToken, config.projectName, config.teamId)
|
|
349
|
-
if (project) {
|
|
350
|
-
await vercelFetch(`/v9/projects/${project.id}`, vercelToken, config.teamId, {
|
|
351
|
-
method: 'DELETE',
|
|
352
|
-
})
|
|
353
|
-
console.log(` Deleted project "${config.projectName}"`)
|
|
354
|
-
} else {
|
|
355
|
-
console.log(` Project "${config.projectName}" not found — skipping`)
|
|
356
|
-
}
|
|
357
|
-
},
|
|
358
|
-
})
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "vercel",
|
|
3
|
-
"description": "Vercel project + deploy module",
|
|
4
|
-
"files": [{ "path": "index.ts" }],
|
|
5
|
-
"dependencies": {
|
|
6
|
-
"zod": "^3.24.0"
|
|
7
|
-
},
|
|
8
|
-
"devDependencies": {
|
|
9
|
-
"vercel": "^50.0.0"
|
|
10
|
-
},
|
|
11
|
-
"secrets": ["VERCEL_TOKEN"],
|
|
12
|
-
"signupUrl": "https://vercel.com/signup",
|
|
13
|
-
"tokenUrl": "https://vercel.com/account/tokens",
|
|
14
|
-
"instructions": "Add VERCEL_TOKEN to packages/infra/environments/<env>/secrets.yaml. The vercel CLI is installed as a devDependency for deploys."
|
|
15
|
-
}
|