@zabaca/zbc 0.3.2 → 0.4.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 +1 -1
- package/src/commands/add.ts +3 -1
- package/src/commands/destroy.ts +8 -9
- package/src/engine/destroy.ts +22 -2
- package/templates/infra/modules/cloudflare/index.ts +163 -0
- package/templates/infra/modules/cloudflare/registry.json +15 -0
- package/templates/infra/modules/nats-server/index.ts +20 -34
- package/templates/infra/modules/nats-server/registry.json +4 -6
package/package.json
CHANGED
package/src/commands/add.ts
CHANGED
|
@@ -28,7 +28,9 @@ async function resolveBundledModuleDir(name: string): Promise<string> {
|
|
|
28
28
|
const registry = path.join(dir, 'registry.json')
|
|
29
29
|
if (await Bun.file(registry).exists()) return dir
|
|
30
30
|
}
|
|
31
|
-
throw new Error(
|
|
31
|
+
throw new Error(
|
|
32
|
+
`Module "${name}" not found in built-in registry. Available: cloudflare, nats-server, turso, vercel.`,
|
|
33
|
+
)
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
function bunAdd(
|
package/src/commands/destroy.ts
CHANGED
|
@@ -15,6 +15,11 @@ export const destroyCommand = defineCommand({
|
|
|
15
15
|
description: 'Environment name (e.g., preview)',
|
|
16
16
|
required: true,
|
|
17
17
|
},
|
|
18
|
+
instance: {
|
|
19
|
+
type: 'positional',
|
|
20
|
+
description: 'Specific instance to destroy (omit to destroy the whole environment)',
|
|
21
|
+
required: false,
|
|
22
|
+
},
|
|
18
23
|
},
|
|
19
24
|
async run({ args }) {
|
|
20
25
|
const projectRoot = await findProjectRoot()
|
|
@@ -27,16 +32,10 @@ export const destroyCommand = defineCommand({
|
|
|
27
32
|
process.exit(1)
|
|
28
33
|
}
|
|
29
34
|
|
|
30
|
-
const envDir = path.join(
|
|
31
|
-
projectRoot,
|
|
32
|
-
'packages',
|
|
33
|
-
'infra',
|
|
34
|
-
'environments',
|
|
35
|
-
args.env,
|
|
36
|
-
)
|
|
35
|
+
const envDir = path.join(projectRoot, 'packages', 'infra', 'environments', args.env)
|
|
37
36
|
|
|
38
|
-
console.log(`Destroying ${args.env}...`)
|
|
39
|
-
await destroyEnvironment(projectRoot, envDir)
|
|
37
|
+
console.log(`Destroying ${args.env}${args.instance ? ` (instance: ${args.instance})` : ''}...`)
|
|
38
|
+
await destroyEnvironment(projectRoot, envDir, args.instance)
|
|
40
39
|
console.log('\nDone.')
|
|
41
40
|
},
|
|
42
41
|
})
|
package/src/engine/destroy.ts
CHANGED
|
@@ -3,10 +3,30 @@ import { discoverInstances } from './discover'
|
|
|
3
3
|
import { resolveOrder } from './resolve'
|
|
4
4
|
import { loadSecrets } from './secrets'
|
|
5
5
|
|
|
6
|
-
export async function destroyEnvironment(
|
|
6
|
+
export async function destroyEnvironment(
|
|
7
|
+
projectRoot: string,
|
|
8
|
+
envDir: string,
|
|
9
|
+
target?: string,
|
|
10
|
+
): Promise<void> {
|
|
7
11
|
const instances = await discoverInstances(envDir)
|
|
8
12
|
const sorted = resolveOrder(instances)
|
|
9
|
-
|
|
13
|
+
let reversed = [...sorted].reverse()
|
|
14
|
+
|
|
15
|
+
// Targeted destroy: tear down ONLY the named instance. Unlike apply, we do
|
|
16
|
+
// NOT pull in the dependency closure, since a thing's dependencies are
|
|
17
|
+
// usually shared infra you don't want destroyed alongside it. Without this filter,
|
|
18
|
+
// `zbc destroy <env> <instance>` silently ignored the instance arg and
|
|
19
|
+
// destroyed the entire environment.
|
|
20
|
+
if (target) {
|
|
21
|
+
const found = reversed.find((i) => i.name === target)
|
|
22
|
+
if (!found) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
`Instance "${target}" not found. Available: ${instances.map((i) => i.name).join(', ')}`,
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
reversed = [found]
|
|
28
|
+
}
|
|
29
|
+
|
|
10
30
|
const secrets = await loadSecrets(envDir)
|
|
11
31
|
|
|
12
32
|
for (const instance of reversed) {
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
import * as fs from 'node:fs'
|
|
3
|
+
import { execFileSync, execSync } 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 vercel/turso/lima-engine
|
|
12
|
+
* modules: `apply` runs on the operator machine, reads CF creds from
|
|
13
|
+
* `ctx.secrets`, runs an optional local build, then shells `wrangler deploy` in
|
|
14
|
+
* the package's own directory. The Worker TOPOLOGY (name, assets binding,
|
|
15
|
+
* durable_objects, containers, migrations) lives in that package's
|
|
16
|
+
* `wrangler.jsonc` — wrangler is the source of truth for it, not this module.
|
|
17
|
+
* That keeps the module reusable for the eventual Astro-off-Vercel migration
|
|
18
|
+
* (a plain assets Worker) as well as the container-backed payloads.
|
|
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
|
+
|
|
32
|
+
/** Resolve the wrangler binary: prefer the package-local one, else `bunx`. */
|
|
33
|
+
function resolveWrangler(workdir: string): { cmd: string; pre: string[] } {
|
|
34
|
+
const local = path.join(workdir, 'node_modules', '.bin', 'wrangler')
|
|
35
|
+
if (fs.existsSync(local)) return { cmd: local, pre: [] }
|
|
36
|
+
// Fall back to bunx; --bun keeps it on the bun runtime already in use.
|
|
37
|
+
return { cmd: 'bunx', pre: ['--bun', 'wrangler'] }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Run wrangler in `workdir` with CF creds in the env; return captured stdout. */
|
|
41
|
+
function wrangler(workdir: string, args: string[], env: NodeJS.ProcessEnv, input?: string): string {
|
|
42
|
+
const { cmd, pre } = resolveWrangler(workdir)
|
|
43
|
+
try {
|
|
44
|
+
const out = execFileSync(cmd, [...pre, ...args], {
|
|
45
|
+
cwd: workdir,
|
|
46
|
+
env,
|
|
47
|
+
input,
|
|
48
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
49
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
50
|
+
})
|
|
51
|
+
return out.toString()
|
|
52
|
+
} catch (err: unknown) {
|
|
53
|
+
const stderr = (err as { stderr?: Buffer }).stderr?.toString() ?? ''
|
|
54
|
+
const stdout = (err as { stdout?: Buffer }).stdout?.toString() ?? ''
|
|
55
|
+
throw new Error(
|
|
56
|
+
`wrangler ${args.join(' ')} failed:\n${stderr || stdout || (err as Error).message}`,
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const buildSchema = z.object({
|
|
62
|
+
command: z.string(),
|
|
63
|
+
cwd: z.string().optional(),
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
export const cloudflareModule = defineModule({
|
|
67
|
+
name: 'cloudflare',
|
|
68
|
+
configSchema: z.object({
|
|
69
|
+
/** Package dir (relative to projectRoot) that holds wrangler.jsonc. */
|
|
70
|
+
workdir: z.string(),
|
|
71
|
+
/**
|
|
72
|
+
* Cloudflare account id. Not a secret (it appears in the dashboard URL), so
|
|
73
|
+
* it lives in config — only the API token is held in secrets.yaml.
|
|
74
|
+
*/
|
|
75
|
+
accountId: z.string(),
|
|
76
|
+
/** Optional local build run before deploy (e.g. `vite build` for assets). */
|
|
77
|
+
build: buildSchema.optional(),
|
|
78
|
+
/**
|
|
79
|
+
* Worker secrets to push after deploy. Each entry names a key in this
|
|
80
|
+
* environment's secrets.yaml; the same name becomes a Worker secret
|
|
81
|
+
* binding (read at runtime as `env.<NAME>`). Pushed via `wrangler secret
|
|
82
|
+
* put` with the value piped through stdin.
|
|
83
|
+
*/
|
|
84
|
+
workerSecrets: z.array(z.string()).default([]),
|
|
85
|
+
/**
|
|
86
|
+
* For container-backed Workers: roll the running container to the new image
|
|
87
|
+
* IMMEDIATELY on deploy (`--containers-rollout immediate`). The wrangler
|
|
88
|
+
* default is a GRADUAL rollout, which never drains a single always-warm,
|
|
89
|
+
* DO-bound container — so a redeployed image silently never takes effect
|
|
90
|
+
* until the container idle-sleeps. Set true whenever the image matters at
|
|
91
|
+
* deploy time. No-op for asset-only Workers.
|
|
92
|
+
*/
|
|
93
|
+
immediateContainerRollout: z.boolean().default(false),
|
|
94
|
+
}),
|
|
95
|
+
outputs: z.object({
|
|
96
|
+
deployUrl: z.string(),
|
|
97
|
+
}),
|
|
98
|
+
async apply(config, ctx) {
|
|
99
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
100
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
101
|
+
|
|
102
|
+
const env: NodeJS.ProcessEnv = {
|
|
103
|
+
...process.env,
|
|
104
|
+
CLOUDFLARE_API_TOKEN: apiToken,
|
|
105
|
+
CLOUDFLARE_ACCOUNT_ID: config.accountId,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
109
|
+
|
|
110
|
+
// 1. Optional local build (assets). Inherit stdio so build output streams.
|
|
111
|
+
if (config.build) {
|
|
112
|
+
const buildCwd = path.resolve(ctx.projectRoot, config.build.cwd ?? config.workdir)
|
|
113
|
+
console.log(
|
|
114
|
+
` Building: ${config.build.command} (in ${path.relative(ctx.projectRoot, buildCwd) || '.'})`,
|
|
115
|
+
)
|
|
116
|
+
execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit', env })
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 2. Deploy. Creates/updates the Worker script (+ assets, DO, container).
|
|
120
|
+
const deployArgs = ['deploy']
|
|
121
|
+
if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
|
|
122
|
+
console.log(
|
|
123
|
+
` Deploying via wrangler (in ${config.workdir})${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}`,
|
|
124
|
+
)
|
|
125
|
+
const out = wrangler(workdir, deployArgs, env)
|
|
126
|
+
const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
|
|
127
|
+
const deployUrl = urlMatch?.[0] ?? ''
|
|
128
|
+
console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
|
|
129
|
+
|
|
130
|
+
// 3. Push Worker secrets (after deploy: the script must exist first). Value
|
|
131
|
+
// piped via stdin so it never lands in a command string or the log.
|
|
132
|
+
for (const name of config.workerSecrets) {
|
|
133
|
+
const value = ctx.secrets[name]
|
|
134
|
+
if (!value) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
`workerSecrets references "${name}" but it's missing from this environment's secrets.yaml`,
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
wrangler(workdir, ['secret', 'put', name], env, value)
|
|
140
|
+
console.log(` Set Worker secret: ${name}`)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return { deployUrl }
|
|
144
|
+
},
|
|
145
|
+
async destroy(config, ctx) {
|
|
146
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
147
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
148
|
+
const env: NodeJS.ProcessEnv = {
|
|
149
|
+
...process.env,
|
|
150
|
+
CLOUDFLARE_API_TOKEN: apiToken,
|
|
151
|
+
CLOUDFLARE_ACCOUNT_ID: config.accountId,
|
|
152
|
+
}
|
|
153
|
+
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
154
|
+
// `wrangler delete` removes the Worker (and its DO/container). Non-fatal if
|
|
155
|
+
// already gone.
|
|
156
|
+
try {
|
|
157
|
+
wrangler(workdir, ['delete', '--force'], env)
|
|
158
|
+
console.log(' Deleted Worker')
|
|
159
|
+
} catch (err) {
|
|
160
|
+
console.log(` Worker delete skipped: ${(err as Error).message}`)
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cloudflare",
|
|
3
|
+
"description": "Cloudflare Worker deploy module (optional static assets, Durable Object, Container)",
|
|
4
|
+
"files": [{ "path": "index.ts" }],
|
|
5
|
+
"dependencies": {
|
|
6
|
+
"zod": "^3.24.0"
|
|
7
|
+
},
|
|
8
|
+
"devDependencies": {
|
|
9
|
+
"wrangler": "^4.0.0"
|
|
10
|
+
},
|
|
11
|
+
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
12
|
+
"signupUrl": "https://dash.cloudflare.com/sign-up",
|
|
13
|
+
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
14
|
+
"instructions": "Add CLOUDFLARE_API_TOKEN to packages/infra/environments/<env>/secrets.yaml; set accountId in the instance config (not a secret). The Worker topology lives in the package's own wrangler.jsonc, which is the source of truth for it. Container-backed Workers need Docker running locally at apply time and a Workers Paid plan with Containers enabled."
|
|
15
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
1
2
|
import { z } from 'zod'
|
|
2
|
-
import { createOperator, createAccount, fromSeed } from '@nats-io/nkeys'
|
|
3
|
-
import { encodeOperator, encodeAccount } from '@nats-io/jwt'
|
|
4
3
|
import { defineModule } from '../../src/define-module'
|
|
5
4
|
|
|
6
5
|
const FLY_API = 'https://api.machines.dev'
|
|
7
6
|
const FLY_GRAPHQL = 'https://api.fly.io/graphql'
|
|
7
|
+
const NATS_USER = 'app'
|
|
8
8
|
const MACHINE_TAG = { 'managed-by': 'zbc', instance: 'nats' } as const
|
|
9
9
|
|
|
10
10
|
interface FlyApp {
|
|
@@ -93,15 +93,9 @@ async function ensureIPs(appName: string, token: string): Promise<void> {
|
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
-
function renderConf(
|
|
96
|
+
function renderConf(): string {
|
|
97
97
|
return `# Managed by zbc — do not edit by hand.
|
|
98
98
|
|
|
99
|
-
operator: ${operatorJWT}
|
|
100
|
-
resolver: MEMORY
|
|
101
|
-
resolver_preload: {
|
|
102
|
-
${accountPub}: ${accountJWT}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
99
|
http_port: 8222
|
|
106
100
|
|
|
107
101
|
websocket {
|
|
@@ -109,6 +103,11 @@ websocket {
|
|
|
109
103
|
no_tls: true
|
|
110
104
|
}
|
|
111
105
|
|
|
106
|
+
authorization {
|
|
107
|
+
user: ${NATS_USER}
|
|
108
|
+
password: $NATS_PASSWORD
|
|
109
|
+
}
|
|
110
|
+
|
|
112
111
|
max_payload: 1MB
|
|
113
112
|
write_deadline: "10s"
|
|
114
113
|
`
|
|
@@ -131,35 +130,23 @@ export const natsServerModule = defineModule({
|
|
|
131
130
|
}),
|
|
132
131
|
outputs: z.object({
|
|
133
132
|
url: z.string(),
|
|
134
|
-
|
|
135
|
-
|
|
133
|
+
user: z.string(),
|
|
134
|
+
password: z.string(),
|
|
136
135
|
}),
|
|
137
136
|
async apply(config, ctx) {
|
|
138
137
|
const flyToken = ctx.secrets['FLY_API_TOKEN']
|
|
139
138
|
if (!flyToken) throw new Error('Missing secret: FLY_API_TOKEN')
|
|
140
139
|
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const op = createOperator()
|
|
145
|
-
const ac = createAccount()
|
|
146
|
-
const opSeed = new TextDecoder().decode(op.getSeed())
|
|
147
|
-
const acSeed = new TextDecoder().decode(ac.getSeed())
|
|
140
|
+
const password = ctx.secrets['NATS_PASSWORD']
|
|
141
|
+
if (!password) {
|
|
142
|
+
const generated = randomBytes(32).toString('hex')
|
|
148
143
|
throw new Error(
|
|
149
|
-
`Missing secret:
|
|
150
|
-
` Generated
|
|
151
|
-
`
|
|
152
|
-
` NATS_ACCOUNT_SEED: ${acSeed}\n`,
|
|
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`,
|
|
153
147
|
)
|
|
154
148
|
}
|
|
155
149
|
|
|
156
|
-
const operatorKP = fromSeed(new TextEncoder().encode(operatorSeed))
|
|
157
|
-
const accountKP = fromSeed(new TextEncoder().encode(accountSeed))
|
|
158
|
-
const accountPub = accountKP.getPublicKey()
|
|
159
|
-
|
|
160
|
-
const operatorJWT = await encodeOperator('zbc-operator', operatorKP)
|
|
161
|
-
const accountJWT = await encodeAccount('zbc-account', accountKP, {}, { signer: operatorKP })
|
|
162
|
-
|
|
163
150
|
let app = await flyFetch<FlyApp>(`/v1/apps/${config.appName}`, flyToken)
|
|
164
151
|
if (app) {
|
|
165
152
|
console.log(` Fly app "${config.appName}" already exists`)
|
|
@@ -175,12 +162,11 @@ export const natsServerModule = defineModule({
|
|
|
175
162
|
|
|
176
163
|
const machineConfig = {
|
|
177
164
|
image: 'nats:latest',
|
|
165
|
+
env: { NATS_PASSWORD: password },
|
|
178
166
|
files: [
|
|
179
167
|
{
|
|
180
168
|
guest_path: '/etc/nats/nats-server.conf',
|
|
181
|
-
raw_value: Buffer.from(renderConf(
|
|
182
|
-
'base64',
|
|
183
|
-
),
|
|
169
|
+
raw_value: Buffer.from(renderConf(), 'utf8').toString('base64'),
|
|
184
170
|
},
|
|
185
171
|
],
|
|
186
172
|
init: { cmd: ['-c', '/etc/nats/nats-server.conf'] },
|
|
@@ -261,8 +247,8 @@ export const natsServerModule = defineModule({
|
|
|
261
247
|
|
|
262
248
|
return {
|
|
263
249
|
url: `wss://${config.appName}.fly.dev`,
|
|
264
|
-
|
|
265
|
-
|
|
250
|
+
user: NATS_USER,
|
|
251
|
+
password,
|
|
266
252
|
}
|
|
267
253
|
},
|
|
268
254
|
async destroy(config, ctx) {
|
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nats-server",
|
|
3
|
-
"description": "Self-hosted NATS pub/sub server on Fly.io (WebSocket,
|
|
3
|
+
"description": "Self-hosted NATS pub/sub server on Fly.io (WebSocket, single shared cred)",
|
|
4
4
|
"files": [{ "path": "index.ts" }],
|
|
5
5
|
"dependencies": {
|
|
6
|
-
"zod": "^3.24.0"
|
|
7
|
-
"@nats-io/jwt": "^0.0.11",
|
|
8
|
-
"@nats-io/nkeys": "^2.0.3"
|
|
6
|
+
"zod": "^3.24.0"
|
|
9
7
|
},
|
|
10
|
-
"secrets": ["FLY_API_TOKEN", "
|
|
8
|
+
"secrets": ["FLY_API_TOKEN", "NATS_PASSWORD"],
|
|
11
9
|
"signupUrl": "https://fly.io/app/sign-up",
|
|
12
10
|
"tokenUrl": "https://fly.io/user/personal_access_tokens",
|
|
13
|
-
"instructions": "Add FLY_API_TOKEN to packages/infra/environments/<env>/secrets.yaml.
|
|
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."
|
|
14
12
|
}
|