@zabaca/zbc 0.1.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/bin/zbc.js +2 -0
- package/package.json +27 -0
- package/src/commands/add.ts +139 -0
- package/src/commands/apply.ts +47 -0
- package/src/commands/destroy.ts +42 -0
- package/src/commands/init.ts +129 -0
- package/src/engine/apply.ts +35 -0
- package/src/engine/destroy.ts +29 -0
- package/src/engine/discover.ts +33 -0
- package/src/engine/resolve.ts +78 -0
- package/src/engine/secrets.ts +33 -0
- package/src/index.ts +22 -0
- package/src/infra-types.ts +38 -0
- package/src/utils/copy-template.ts +82 -0
- package/src/utils/detect-mode.ts +54 -0
- package/src/utils/find-project-root.ts +18 -0
- package/src/utils/load-config.ts +12 -0
- package/templates/gitignore +8 -0
- package/templates/infra/modules/turso/index.ts +118 -0
- package/templates/infra/modules/turso/registry.json +17 -0
- package/templates/infra/modules/vercel/index.ts +358 -0
- package/templates/infra/modules/vercel/registry.json +15 -0
- package/templates/infra/package.json +15 -0
- package/templates/infra/src/config.ts +8 -0
- package/templates/infra/src/define-module.ts +34 -0
- package/templates/infra/src/index.ts +3 -0
- package/templates/infra/src/types.ts +36 -0
- package/templates/infra/tsconfig.json +9 -0
- package/templates/root/package.json +10 -0
- package/templates/root/tsconfig.json +17 -0
- package/templates/sops.yaml +11 -0
- package/templates/workflows/preview.yml +52 -0
- package/templates/workflows/production.yml +28 -0
- package/templates/zbc.config.ts +6 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
import * as fs from 'node:fs/promises'
|
|
3
|
+
|
|
4
|
+
interface CopyOptions {
|
|
5
|
+
/** {{KEY}} → value substitution applied to the file body. */
|
|
6
|
+
vars?: Record<string, string>
|
|
7
|
+
/** Override skip-if-exists behavior. Default true. */
|
|
8
|
+
skipIfExists?: boolean
|
|
9
|
+
/** Directory/file basenames to skip (e.g. ['modules']). */
|
|
10
|
+
exclude?: string[]
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function substitute(body: string, vars: Record<string, string>): string {
|
|
14
|
+
return body.replace(/\{\{([A-Z0-9_]+)\}\}/g, (match, key: string) => {
|
|
15
|
+
return vars[key] ?? match
|
|
16
|
+
})
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Copy a single template file. Returns true if written, false if skipped.
|
|
21
|
+
* Always logs the action.
|
|
22
|
+
*/
|
|
23
|
+
export async function copyTemplateFile(
|
|
24
|
+
sourcePath: string,
|
|
25
|
+
destPath: string,
|
|
26
|
+
opts: CopyOptions = {},
|
|
27
|
+
): Promise<boolean> {
|
|
28
|
+
const skipIfExists = opts.skipIfExists !== false
|
|
29
|
+
|
|
30
|
+
const destFile = Bun.file(destPath)
|
|
31
|
+
if (skipIfExists && (await destFile.exists())) {
|
|
32
|
+
console.log(` skip ${path.relative(process.cwd(), destPath)} (exists)`)
|
|
33
|
+
return false
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let body = await Bun.file(sourcePath).text()
|
|
37
|
+
if (opts.vars) body = substitute(body, opts.vars)
|
|
38
|
+
|
|
39
|
+
await fs.mkdir(path.dirname(destPath), { recursive: true })
|
|
40
|
+
await Bun.write(destPath, body)
|
|
41
|
+
console.log(` write ${path.relative(process.cwd(), destPath)}`)
|
|
42
|
+
return true
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Recursively copy a directory of templates. Mirrors structure under destDir.
|
|
47
|
+
* Optional rename map maps source basenames to dest names (e.g. `gitignore` →
|
|
48
|
+
* `.gitignore`).
|
|
49
|
+
*/
|
|
50
|
+
export async function copyTemplateDir(
|
|
51
|
+
sourceDir: string,
|
|
52
|
+
destDir: string,
|
|
53
|
+
opts: CopyOptions & { rename?: Record<string, string> } = {},
|
|
54
|
+
): Promise<void> {
|
|
55
|
+
const rename = opts.rename ?? {}
|
|
56
|
+
const exclude = new Set(opts.exclude ?? [])
|
|
57
|
+
const entries = await fs.readdir(sourceDir, { withFileTypes: true })
|
|
58
|
+
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
if (exclude.has(entry.name)) continue
|
|
61
|
+
const srcPath = path.join(sourceDir, entry.name)
|
|
62
|
+
const destName = rename[entry.name] ?? entry.name
|
|
63
|
+
const destPath = path.join(destDir, destName)
|
|
64
|
+
|
|
65
|
+
if (entry.isDirectory()) {
|
|
66
|
+
await copyTemplateDir(srcPath, destPath, opts)
|
|
67
|
+
} else {
|
|
68
|
+
await copyTemplateFile(srcPath, destPath, opts)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Resolve the bundled-templates directory relative to this CLI install. */
|
|
74
|
+
export function templatesRoot(): string {
|
|
75
|
+
// import.meta.dir = .../packages/cli/src/utils → templates at ../../templates
|
|
76
|
+
return path.resolve(import.meta.dir, '../../templates')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Path to bundled modules: packages/cli/templates/infra/modules/. */
|
|
80
|
+
export function bundledModulesCandidates(): string[] {
|
|
81
|
+
return [path.resolve(import.meta.dir, '../../templates/infra/modules')]
|
|
82
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
|
|
3
|
+
export type InitMode =
|
|
4
|
+
| { kind: 'greenfield' }
|
|
5
|
+
| { kind: 'monorepo' }
|
|
6
|
+
| { kind: 'incompatible'; reason: string }
|
|
7
|
+
|
|
8
|
+
interface PackageJson {
|
|
9
|
+
workspaces?: string[] | { packages?: string[] }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function workspaceGlobs(pkg: PackageJson): string[] {
|
|
13
|
+
if (!pkg.workspaces) return []
|
|
14
|
+
if (Array.isArray(pkg.workspaces)) return pkg.workspaces
|
|
15
|
+
return pkg.workspaces.packages ?? []
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function hasPackagesGlob(globs: string[]): boolean {
|
|
19
|
+
return globs.some((g) => g === 'packages/*' || g === 'packages/**' || g.startsWith('packages/'))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function detectMode(cwd: string): Promise<InitMode> {
|
|
23
|
+
const pkgPath = path.join(cwd, 'package.json')
|
|
24
|
+
const pkgFile = Bun.file(pkgPath)
|
|
25
|
+
|
|
26
|
+
if (!(await pkgFile.exists())) {
|
|
27
|
+
return { kind: 'greenfield' }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let pkg: PackageJson
|
|
31
|
+
try {
|
|
32
|
+
pkg = (await pkgFile.json()) as PackageJson
|
|
33
|
+
} catch {
|
|
34
|
+
return { kind: 'incompatible', reason: 'package.json is not valid JSON' }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const globs = workspaceGlobs(pkg)
|
|
38
|
+
if (globs.length === 0) {
|
|
39
|
+
return {
|
|
40
|
+
kind: 'incompatible',
|
|
41
|
+
reason:
|
|
42
|
+
'package.json exists but has no `workspaces` field. v1 only supports greenfield or existing Bun workspaces. Add `"workspaces": ["packages/*"]` and re-run.',
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!hasPackagesGlob(globs)) {
|
|
47
|
+
return {
|
|
48
|
+
kind: 'incompatible',
|
|
49
|
+
reason: `workspaces glob does not include packages/* (found: ${globs.join(', ')}). Add a packages/* glob and re-run.`,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return { kind: 'monorepo' }
|
|
54
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
|
|
3
|
+
export async function findProjectRoot(from?: string): Promise<string> {
|
|
4
|
+
let dir = from ?? process.cwd()
|
|
5
|
+
|
|
6
|
+
while (true) {
|
|
7
|
+
const configPath = path.join(dir, 'zbc.config.ts')
|
|
8
|
+
if (await Bun.file(configPath).exists()) {
|
|
9
|
+
return dir
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const parent = path.dirname(dir)
|
|
13
|
+
if (parent === dir) {
|
|
14
|
+
throw new Error('Could not find zbc.config.ts in any parent directory')
|
|
15
|
+
}
|
|
16
|
+
dir = parent
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
|
|
3
|
+
interface ZbcConfig {
|
|
4
|
+
project: string
|
|
5
|
+
environments: string[]
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export async function loadConfig(projectRoot: string): Promise<ZbcConfig> {
|
|
9
|
+
const configPath = path.join(projectRoot, 'zbc.config.ts')
|
|
10
|
+
const mod = await import(configPath)
|
|
11
|
+
return mod.default as ZbcConfig
|
|
12
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { createClient } from '@tursodatabase/api'
|
|
3
|
+
import { defineModule } from '../../src/define-module'
|
|
4
|
+
|
|
5
|
+
export const tursoModule = defineModule({
|
|
6
|
+
name: 'turso',
|
|
7
|
+
configSchema: z.object({
|
|
8
|
+
orgName: z.string(),
|
|
9
|
+
dbName: z.string(),
|
|
10
|
+
group: z.string().default('default'),
|
|
11
|
+
primaryLocation: z.string().default('iad'),
|
|
12
|
+
ephemeral: z.boolean().default(false),
|
|
13
|
+
/**
|
|
14
|
+
* Path to a Drizzle migrations folder, relative to the monorepo root
|
|
15
|
+
* (resolved via ctx.projectRoot). When provided, apply() runs migrations
|
|
16
|
+
* after database creation. Idempotent.
|
|
17
|
+
*/
|
|
18
|
+
migrationsDir: z.string().optional(),
|
|
19
|
+
}),
|
|
20
|
+
outputs: z.object({
|
|
21
|
+
databaseUrl: z.string(),
|
|
22
|
+
authToken: z.string(),
|
|
23
|
+
}),
|
|
24
|
+
async apply(config, ctx) {
|
|
25
|
+
const apiToken = ctx.secrets['TURSO_API_TOKEN']
|
|
26
|
+
if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
|
|
27
|
+
|
|
28
|
+
const turso = createClient({ org: config.orgName, token: apiToken })
|
|
29
|
+
|
|
30
|
+
// For ephemeral databases, destroy first to get a clean state
|
|
31
|
+
if (config.ephemeral) {
|
|
32
|
+
try {
|
|
33
|
+
await turso.databases.delete(config.dbName)
|
|
34
|
+
console.log(` Deleted ephemeral database "${config.dbName}"`)
|
|
35
|
+
} catch {
|
|
36
|
+
// Database didn't exist — that's fine
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Check if database already exists
|
|
41
|
+
const databases = await turso.databases.list()
|
|
42
|
+
const existing = databases.find((db) => db.name === config.dbName)
|
|
43
|
+
|
|
44
|
+
if (existing) {
|
|
45
|
+
console.log(` Database "${config.dbName}" already exists`)
|
|
46
|
+
|
|
47
|
+
if (existing.group && existing.group !== config.group) {
|
|
48
|
+
console.warn(` ⚠ Drift: group is "${existing.group}" but config says "${config.group}"`)
|
|
49
|
+
}
|
|
50
|
+
if (existing.primaryRegion && existing.primaryRegion !== config.primaryLocation) {
|
|
51
|
+
console.warn(
|
|
52
|
+
` ⚠ Drift: location is "${existing.primaryRegion}" but config says "${config.primaryLocation}"`,
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
} else {
|
|
56
|
+
// Ensure group exists
|
|
57
|
+
try {
|
|
58
|
+
const groups = await turso.groups.list()
|
|
59
|
+
const groupExists = groups.some((g) => g.name === config.group)
|
|
60
|
+
if (!groupExists) {
|
|
61
|
+
await turso.groups.create(config.group, config.primaryLocation)
|
|
62
|
+
console.log(` Created group "${config.group}" at ${config.primaryLocation}`)
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
// Group may already exist — continue
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
await turso.databases.create(config.dbName, { group: config.group })
|
|
69
|
+
console.log(` Created database "${config.dbName}" in group "${config.group}"`)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Generate an auth token
|
|
73
|
+
const tokenResponse = await turso.databases.createToken(config.dbName, {
|
|
74
|
+
authorization: 'full-access',
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const hostname = existing?.hostname ?? `${config.dbName}-${config.orgName}.turso.io`
|
|
78
|
+
const databaseUrl = `libsql://${hostname}`
|
|
79
|
+
|
|
80
|
+
if (config.migrationsDir) {
|
|
81
|
+
const { resolve } = await import('node:path')
|
|
82
|
+
const { createClient: createLibsqlClient } = await import('@libsql/client')
|
|
83
|
+
const { drizzle } = await import('drizzle-orm/libsql')
|
|
84
|
+
const { migrate } = await import('drizzle-orm/libsql/migrator')
|
|
85
|
+
|
|
86
|
+
const folder = resolve(ctx.projectRoot, config.migrationsDir)
|
|
87
|
+
const migrationClient = createLibsqlClient({
|
|
88
|
+
url: databaseUrl,
|
|
89
|
+
authToken: tokenResponse.jwt,
|
|
90
|
+
})
|
|
91
|
+
const migrationDb = drizzle(migrationClient)
|
|
92
|
+
|
|
93
|
+
console.log(` Applying migrations from ${folder}`)
|
|
94
|
+
await migrate(migrationDb, { migrationsFolder: folder })
|
|
95
|
+
console.log(` ✓ Migrations applied`)
|
|
96
|
+
|
|
97
|
+
migrationClient.close()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
databaseUrl,
|
|
102
|
+
authToken: tokenResponse.jwt,
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
async destroy(config, ctx) {
|
|
106
|
+
const apiToken = ctx.secrets['TURSO_API_TOKEN']
|
|
107
|
+
if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
|
|
108
|
+
|
|
109
|
+
const turso = createClient({ org: config.orgName, token: apiToken })
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
await turso.databases.delete(config.dbName)
|
|
113
|
+
console.log(` Deleted database "${config.dbName}"`)
|
|
114
|
+
} catch {
|
|
115
|
+
console.log(` Database "${config.dbName}" not found — skipping`)
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "turso",
|
|
3
|
+
"description": "Turso database module",
|
|
4
|
+
"files": [{ "path": "index.ts" }],
|
|
5
|
+
"dependencies": {
|
|
6
|
+
"zod": "^3.24.0",
|
|
7
|
+
"@tursodatabase/api": "^2.0.0"
|
|
8
|
+
},
|
|
9
|
+
"optionalDependencies": {
|
|
10
|
+
"@libsql/client": "^0.14.0",
|
|
11
|
+
"drizzle-orm": "^0.36.0"
|
|
12
|
+
},
|
|
13
|
+
"secrets": ["TURSO_API_TOKEN"],
|
|
14
|
+
"signupUrl": "https://turso.tech",
|
|
15
|
+
"tokenUrl": "https://app.turso.tech/account/api-tokens",
|
|
16
|
+
"instructions": "Add TURSO_API_TOKEN to packages/infra/environments/<env>/secrets.yaml. Optional deps (@libsql/client, drizzle-orm) only needed if using migrationsDir."
|
|
17
|
+
}
|
|
@@ -0,0 +1,358 @@
|
|
|
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
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
}
|