create-svc 0.1.15 → 0.1.16

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-svc",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
4
4
  "description": "Local microservice bootstrap CLI for Cloud Run and Workers services with Neon-backed data.",
5
5
  "module": "index.ts",
6
6
  "type": "module",
@@ -84,7 +84,7 @@ test("scaffolds all runtime/framework variants with shared cloudrun config", asy
84
84
 
85
85
  const deployScript = await Bun.file(join(generatedRoot, "scripts", "cloudrun", "lib.ts")).text();
86
86
  expect(deployScript).toContain('--billing-project", config.project.quotaProjectId');
87
- expect(deployScript).toContain('config.project.mode === "use_existing"');
87
+ expect(deployScript).toContain('projectMode === "use_existing"');
88
88
  expect(deployScript).toContain("serviceDomain");
89
89
  expect(deployScript).toContain("ensureProductionDomainMapping");
90
90
  expect(deployScript).toContain('"domain-mappings",');
@@ -96,7 +96,10 @@ test("scaffolds all runtime/framework variants with shared cloudrun config", asy
96
96
  expect(await Bun.file(join(generatedRoot, "scripts", "cloudrun", "integrations.ts")).exists()).toBeFalse();
97
97
  const destroyScript = await Bun.file(join(generatedRoot, "scripts", "cloudrun", "cleanup.ts")).text();
98
98
  expect(destroyScript).toContain("assertOwnedResource");
99
- expect(destroyScript).toContain("assertProductionDomainMappingOwned");
99
+ expect(destroyScript).toContain("Planning resources to destroy");
100
+ expect(destroyScript).toContain("Resources selected for destroy");
101
+ expect(destroyScript).toContain("Destroy cannot continue until resource discovery succeeds");
102
+ expect(destroyScript).toContain("deleteAuthResourceServer");
100
103
  expect(destroyScript).toContain("deleteGrafanaResources");
101
104
  expect(destroyScript).toContain('gcx", ["resources", "delete"');
102
105
  expect(destroyScript).toContain("config.temporal.apiKeySecretName");
@@ -135,6 +138,7 @@ test("scaffolds all runtime/framework variants with shared cloudrun config", asy
135
138
  expect(envExample).toContain("AUTH_ENABLED=false");
136
139
  expect(envExample).toContain("AUTH_AUDIENCE=api://dns-api");
137
140
  expect(envExample).toContain("CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID=");
141
+ expect(envExample).toContain("VAULT_AUTHCTL_ACCESS_PATH=prod/apps/auth/authctl/cloudflare-access");
138
142
  expect(envExample).toContain("TEMPORAL_API_KEY=");
139
143
  expect(envExample).toContain("The base waitlist service does not require");
140
144
  expect(envExample).not.toContain("ATTACHMENT_BUCKET=");
@@ -146,6 +150,8 @@ test("scaffolds all runtime/framework variants with shared cloudrun config", asy
146
150
 
147
151
  const localEnv = await Bun.file(join(generatedRoot, ".env.local")).text();
148
152
  expect(localEnv).toContain(`DATABASE_URL=postgres://postgres:postgres@127.0.0.1:${localPort}/dns_api?sslmode=disable`);
153
+ expect(localEnv).toContain("VAULT_AUTHCTL_ACCESS_PATH=prod/apps/auth/authctl/cloudflare-access");
154
+ expect(localEnv).toContain("VAULT_NEON_API_KEY_PATH=prod/providers/neon");
149
155
  expect(localEnv).not.toContain("ATTACHMENT_PUBLIC_BASE_URL=");
150
156
 
151
157
  const ciWorkflow = await Bun.file(join(generatedRoot, ".github", "workflows", "ci.yml")).text();
@@ -223,6 +229,9 @@ test("scaffolds all runtime/framework variants with shared cloudrun config", asy
223
229
  expect(authctlScript).toContain("resource-servers");
224
230
  expect(authctlScript).toContain("clients");
225
231
  expect(authctlScript).toContain("defaultClientTargetArgs");
232
+ expect(authctlScript).toContain("deleteAuthResourceServer");
233
+ expect(authctlScript).toContain("readAuthctlAccessVaultField");
234
+ expect(authctlScript).toContain("prod/apps/auth/authctl/cloudflare-access");
226
235
  expect(authctlScript).toContain('existsSync("./node_modules/.bin/authctl") ? "./node_modules/.bin/authctl" : Bun.which("authctl")');
227
236
  expect(authctlScript).not.toContain('defaultAuthResourceServerArgs(), "--yes", "--json"');
228
237
  const authScript = await Bun.file(join(generatedRoot, "src", "auth.ts")).text();
package/src/scaffold.ts CHANGED
@@ -252,6 +252,14 @@ async function writeLocalEnvFile(targetDir: string, replacements: Record<string,
252
252
  "",
253
253
  "DATABASE_URL=postgres://{{LOCAL_DATABASE_USER}}:{{LOCAL_DATABASE_PASSWORD}}@127.0.0.1:{{LOCAL_DATABASE_PORT}}/{{LOCAL_DATABASE_NAME}}?sslmode=disable",
254
254
  "",
255
+ "VAULT_SECRET_MOUNT=secret",
256
+ "VAULT_AUTHCTL_ACCESS_PATH=prod/apps/auth/authctl/cloudflare-access",
257
+ "VAULT_AUTHCTL_ACCESS_BASE_URL_FIELD=AUTH_INTERNAL_BASE_URL",
258
+ "VAULT_AUTHCTL_ACCESS_CLIENT_ID_FIELD=CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID",
259
+ "VAULT_AUTHCTL_ACCESS_CLIENT_SECRET_FIELD=CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET",
260
+ "VAULT_NEON_API_KEY_PATH=prod/providers/neon",
261
+ "VAULT_NEON_API_KEY_FIELD=api_key",
262
+ "",
255
263
  ].join("\n"),
256
264
  replacements
257
265
  );
@@ -104,14 +104,17 @@ The scaffold will use, in order:
104
104
 
105
105
  That keeps stable settings in the repo and keeps the token out of `~/.zshrc`.
106
106
 
107
- For production auth registration, `authctl` also needs the auth service's
108
- Cloudflare Access service token:
107
+ For production auth registration, `authctl` loads the auth service's Cloudflare
108
+ Access service token from Vault by default:
109
109
 
110
- ```bash
111
- export AUTH_INTERNAL_BASE_URL="$(vault kv get -mount=secret -field=AUTH_INTERNAL_BASE_URL prod/apps/auth/authctl/cloudflare-access)"
112
- export CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID="$(vault kv get -mount=secret -field=CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID prod/apps/auth/authctl/cloudflare-access)"
113
- export CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET="$(vault kv get -mount=secret -field=CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET prod/apps/auth/authctl/cloudflare-access)"
114
- ```
110
+ - `VAULT_AUTHCTL_ACCESS_PATH` default `prod/apps/auth/authctl/cloudflare-access`
111
+ - `VAULT_AUTHCTL_ACCESS_BASE_URL_FIELD` default `AUTH_INTERNAL_BASE_URL`
112
+ - `VAULT_AUTHCTL_ACCESS_CLIENT_ID_FIELD` default `CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID`
113
+ - `VAULT_AUTHCTL_ACCESS_CLIENT_SECRET_FIELD` default `CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET`
114
+
115
+ Direct `AUTH_INTERNAL_BASE_URL`, `CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID`,
116
+ and `CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET` env values still override
117
+ Vault when set.
115
118
 
116
119
  Before first production create, verify the installed `authctl` exposes the
117
120
  resource-server control-plane command:
@@ -127,6 +130,7 @@ newer before running `{{COMMAND_BOOTSTRAP}}`.
127
130
  Optional remote-only Vault overrides for Neon admin key lookup:
128
131
 
129
132
  - `VAULT_SECRET_MOUNT` default `secret`
133
+ - `VAULT_AUTHCTL_ACCESS_PATH` default `prod/apps/auth/authctl/cloudflare-access`
130
134
  - `VAULT_NEON_API_KEY_PATH` default `prod/providers/neon`
131
135
  - `VAULT_NEON_API_KEY_FIELD` default `api_key`
132
136
 
@@ -58,10 +58,24 @@ export function runAuthCommand(args: string[]) {
58
58
  "authctl is installed but does not expose resource-server commands; install @anmho/authctl@0.1.1 or newer before managing auth resource servers"
59
59
  );
60
60
  }
61
- if (action === "get" || action === "list") {
61
+ if (action === "get" || action === "list" || action === "delete") {
62
62
  if (!command.actions.includes(action)) {
63
63
  throw new Error(`authctl ${command.subject} does not expose ${action}`);
64
64
  }
65
+ if (action === "delete") {
66
+ authctl([
67
+ command.subject,
68
+ action,
69
+ "--resource-server",
70
+ serviceConfig.auth.resource_server.id,
71
+ "--stage",
72
+ serviceConfig.stage_default,
73
+ "--force",
74
+ "--json",
75
+ ...rest,
76
+ ]);
77
+ return `Auth resource server deleted: ${serviceConfig.auth.resource_server.id}`;
78
+ }
65
79
  authctl([command.subject, action, ...rest]);
66
80
  return `Auth resource server ${action} finished`;
67
81
  }
@@ -87,6 +101,25 @@ export function ensureAuthResourceServer() {
87
101
  return `Auth resource server ready: ${serviceConfig.auth.resource_server.audience}`;
88
102
  }
89
103
 
104
+ export function deleteAuthResourceServer() {
105
+ const command = resolveResourceServerCommand();
106
+ if (!command?.actions.includes("delete")) {
107
+ return "authctl does not expose resource-server delete; auth resource server was not deleted";
108
+ }
109
+
110
+ authctl([
111
+ command.subject,
112
+ "delete",
113
+ "--resource-server",
114
+ serviceConfig.auth.resource_server.id,
115
+ "--stage",
116
+ serviceConfig.stage_default,
117
+ "--force",
118
+ "--json",
119
+ ]);
120
+ return `Auth resource server deleted: ${serviceConfig.auth.resource_server.id}`;
121
+ }
122
+
90
123
  export function runAuthDoctor(): AuthDoctorResult {
91
124
  if (!authctlPath()) {
92
125
  return {
@@ -185,7 +218,7 @@ function resolveResourceServerCommand(): ResourceServerCommand | undefined {
185
218
  if (!help.success || !output.includes(subject)) {
186
219
  continue;
187
220
  }
188
- const actions = ["upsert", "create", "get", "list"].filter((candidate) => output.includes(candidate));
221
+ const actions = ["upsert", "create", "get", "list", "delete"].filter((candidate) => output.includes(candidate));
189
222
  const mutationAction = actions.includes("upsert") ? "upsert" : actions.includes("create") ? "create" : undefined;
190
223
  if (actions.length > 0) {
191
224
  return { subject, mutationAction, actions };
@@ -202,7 +235,7 @@ function authctl(args: string[], options: { allowFailure?: boolean; quiet?: bool
202
235
 
203
236
  const result = Bun.spawnSync([command, ...args], {
204
237
  cwd: process.cwd(),
205
- env: process.env,
238
+ env: authctlEnvironment(),
206
239
  stdin: "inherit",
207
240
  stdout: "pipe",
208
241
  stderr: "pipe",
@@ -232,10 +265,9 @@ function formatAuthctlFailure(args: string[], output: CommandResult) {
232
265
  return [
233
266
  `authctl ${args.join(" ")} failed with exit code ${output.exitCode}`,
234
267
  "authctl reached the auth internal API, but Cloudflare Access rejected the request.",
235
- "Export the authctl Cloudflare Access service token before running service create:",
236
- ' export AUTH_INTERNAL_BASE_URL="$(vault kv get -mount=secret -field=AUTH_INTERNAL_BASE_URL prod/apps/auth/authctl/cloudflare-access)"',
237
- ' export CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID="$(vault kv get -mount=secret -field=CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID prod/apps/auth/authctl/cloudflare-access)"',
238
- ' export CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET="$(vault kv get -mount=secret -field=CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET prod/apps/auth/authctl/cloudflare-access)"',
268
+ "The service CLI tried to load the authctl Access token from Vault.",
269
+ "Verify `vault login` works and that this path is readable:",
270
+ " secret/prod/apps/auth/authctl/cloudflare-access",
239
271
  ].join("\n");
240
272
  }
241
273
 
@@ -245,3 +277,58 @@ function formatAuthctlFailure(args: string[], output: CommandResult) {
245
277
  function authctlPath() {
246
278
  return existsSync("./node_modules/.bin/authctl") ? "./node_modules/.bin/authctl" : Bun.which("authctl");
247
279
  }
280
+
281
+ function authctlEnvironment() {
282
+ const env = { ...process.env };
283
+ const fields = [
284
+ {
285
+ envName: "AUTH_INTERNAL_BASE_URL",
286
+ fieldEnvName: "VAULT_AUTHCTL_ACCESS_BASE_URL_FIELD",
287
+ defaultField: "AUTH_INTERNAL_BASE_URL",
288
+ },
289
+ {
290
+ envName: "CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID",
291
+ fieldEnvName: "VAULT_AUTHCTL_ACCESS_CLIENT_ID_FIELD",
292
+ defaultField: "CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_ID",
293
+ },
294
+ {
295
+ envName: "CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET",
296
+ fieldEnvName: "VAULT_AUTHCTL_ACCESS_CLIENT_SECRET_FIELD",
297
+ defaultField: "CLOUDFLARE_ACCESS_SERVICE_TOKEN_CLIENT_SECRET",
298
+ },
299
+ ];
300
+
301
+ for (const field of fields) {
302
+ if (env[field.envName]?.trim()) {
303
+ continue;
304
+ }
305
+ const value = readAuthctlAccessVaultField(env, env[field.fieldEnvName]?.trim() || field.defaultField);
306
+ if (value) {
307
+ env[field.envName] = value;
308
+ }
309
+ }
310
+
311
+ return env;
312
+ }
313
+
314
+ function readAuthctlAccessVaultField(env: Record<string, string | undefined>, field: string) {
315
+ const vault = Bun.which("vault");
316
+ if (!vault) {
317
+ return "";
318
+ }
319
+
320
+ const mount = env.VAULT_AUTHCTL_ACCESS_MOUNT?.trim() || env.VAULT_SECRET_MOUNT?.trim() || "secret";
321
+ const path = env.VAULT_AUTHCTL_ACCESS_PATH?.trim() || "prod/apps/auth/authctl/cloudflare-access";
322
+ const result = Bun.spawnSync([vault, "kv", "get", `-mount=${mount}`, `-field=${field}`, path], {
323
+ cwd: process.cwd(),
324
+ env,
325
+ stdout: "pipe",
326
+ stderr: "pipe",
327
+ });
328
+
329
+ if (!result.success || !result.stdout) {
330
+ return "";
331
+ }
332
+
333
+ return decoder.decode(result.stdout).trim();
334
+ }
@@ -1,4 +1,5 @@
1
1
  import { confirm, isCancel, log } from "@clack/prompts";
2
+ import { deleteAuthResourceServer } from "../authctl";
2
3
  import { config } from "./config";
3
4
  import { deleteBranch, deleteDatabase, listBranches, resolveNeonConfig } from "./neon";
4
5
  import {
@@ -11,6 +12,7 @@ import {
11
12
  describeCloudRunService,
12
13
  describeProductionDomainMapping,
13
14
  describeSecret,
15
+ formatError,
14
16
  listCloudRunServices,
15
17
  listSecrets,
16
18
  parseCleanupArgs,
@@ -34,18 +36,46 @@ function matchesSecretResource(name: string) {
34
36
  );
35
37
  }
36
38
 
39
+ type PlannedResource = {
40
+ label: string;
41
+ detail?: string;
42
+ };
43
+
44
+ type DestroyPlan = {
45
+ resources: PlannedResource[];
46
+ skipped: PlannedResource[];
47
+ blockers: string[];
48
+ hasProductionDomainMapping: boolean;
49
+ serviceNames: string[];
50
+ secretNames: string[];
51
+ neon?: {
52
+ projectId: string;
53
+ baseBranchId: string;
54
+ databaseName: string;
55
+ branches: Array<{ id: string; name: string }>;
56
+ };
57
+ };
58
+
37
59
  export async function cleanup(args = Bun.argv.slice(2)) {
38
60
  requireCommand("gcloud");
39
61
  requireGcloudAuth();
40
62
 
41
63
  const options = parseCleanupArgs(args);
64
+ const plan = await runStep("Planning resources to destroy", () => buildDestroyPlan(options.destroyProject));
65
+ printDestroyPlan(plan);
66
+ if (plan.blockers.length > 0) {
67
+ throw new Error(["Destroy cannot continue until resource discovery succeeds:", ...plan.blockers.map((blocker) => `- ${blocker}`)].join("\n"));
68
+ }
69
+
42
70
  await requireDestroyConfirmation(options.force);
43
71
 
44
- await runStep(`Verifying production domain mapping ${config.domain.hostname}`, () => assertProductionDomainMappingOwned());
45
- await runStep(`Deleting production domain mapping ${config.domain.hostname}`, () => deleteProductionDomainMapping());
72
+ await runStep(`Deleting auth resource server ${config.serviceName}`, () => deleteAuthResourceServer());
46
73
 
47
- const services = await runStep("Finding Cloud Run services", () => listCloudRunServices());
48
- const serviceNames = services.filter(matchesServiceResource);
74
+ if (plan.hasProductionDomainMapping) {
75
+ await runStep(`Deleting production domain mapping ${config.domain.hostname}`, () => deleteProductionDomainMapping());
76
+ }
77
+
78
+ const serviceNames = plan.serviceNames;
49
79
  await runStep("Deleting Cloud Run services", () => {
50
80
  for (const serviceName of serviceNames) {
51
81
  assertOwnedResource(`Cloud Run service ${serviceName}`, describeCloudRunService(serviceName));
@@ -53,8 +83,7 @@ export async function cleanup(args = Bun.argv.slice(2)) {
53
83
  }
54
84
  });
55
85
 
56
- const secrets = await runStep("Finding service secrets", () => listSecrets());
57
- const secretNames = secrets.filter(matchesSecretResource);
86
+ const secretNames = plan.secretNames;
58
87
  await runStep("Deleting service secrets", () => {
59
88
  for (const secretName of secretNames) {
60
89
  assertOwnedResource(`Secret ${secretName}`, describeSecret(secretName));
@@ -62,24 +91,15 @@ export async function cleanup(args = Bun.argv.slice(2)) {
62
91
  }
63
92
  });
64
93
 
65
- try {
66
- const neon = await runStep("Resolving Neon defaults", () => resolveNeonConfig());
67
- const branches = await runStep("Finding Neon branches", () => listBranches(neon.projectId));
68
- const disposableBranches = branches.filter(
69
- (branch: { name: string }) =>
70
- branch.name.startsWith(`${neon.previewBranchPrefix}-`) || branch.name.startsWith(`${neon.personalBranchPrefix}-`)
71
- );
72
-
94
+ const neonPlan = plan.neon;
95
+ if (neonPlan) {
73
96
  await runStep("Deleting Neon preview and personal branches", async () => {
74
- for (const branch of disposableBranches) {
75
- await deleteBranch(neon.projectId, branch.id);
97
+ for (const branch of neonPlan.branches) {
98
+ await deleteBranch(neonPlan.projectId, branch.id);
76
99
  }
77
100
  });
78
101
 
79
- await runStep("Deleting Neon service database", () => deleteDatabase(neon.projectId, neon.baseBranchId, neon.databaseName));
80
- } catch (error) {
81
- log.step("Skipping Neon cleanup because Neon is not configured");
82
- log.step(error instanceof Error ? error.message : String(error));
102
+ await runStep("Deleting Neon service database", () => deleteDatabase(neonPlan.projectId, neonPlan.baseBranchId, neonPlan.databaseName));
83
103
  }
84
104
 
85
105
  await runStep("Deleting Grafana resources", async () => deleteGrafanaResources());
@@ -97,30 +117,144 @@ export async function cleanup(args = Bun.argv.slice(2)) {
97
117
  return `Destroy finished for ${config.serviceName}`;
98
118
  }
99
119
 
100
- async function deleteGrafanaResources() {
101
- if (!(await Bun.file("./grafana").exists())) {
102
- return "No grafana directory configured";
120
+ async function buildDestroyPlan(destroyProject: boolean): Promise<DestroyPlan> {
121
+ const plan: DestroyPlan = {
122
+ resources: [
123
+ { label: `Auth resource server ${config.serviceName}`, detail: "stage prod" },
124
+ { label: `Runtime service account ${config.runtimeServiceAccount}`, detail: "if it exists" },
125
+ ],
126
+ skipped: [],
127
+ blockers: [],
128
+ hasProductionDomainMapping: false,
129
+ serviceNames: [],
130
+ secretNames: [],
131
+ };
132
+
133
+ planProductionDomainMapping(plan);
134
+ planCloudRunServices(plan);
135
+ planSecrets(plan);
136
+ await planNeon(plan);
137
+ await planGrafana(plan);
138
+
139
+ if (destroyProject) {
140
+ plan.resources.push({ label: `GCP project ${config.project.id}`, detail: "requested with --project" });
103
141
  }
104
- if (!Bun.which("gcx")) {
105
- return "gcx is not installed; Grafana resources were not deleted";
142
+
143
+ return plan;
144
+ }
145
+
146
+ function planProductionDomainMapping(plan: DestroyPlan) {
147
+ try {
148
+ const mapping = describeProductionDomainMapping();
149
+ if (!mapping) {
150
+ plan.skipped.push({ label: `Production domain mapping ${config.domain.hostname}`, detail: "not found" });
151
+ return;
152
+ }
153
+
154
+ const routeName = mapping.spec?.routeName;
155
+ if (routeName !== config.serviceName) {
156
+ plan.blockers.push(`${config.domain.hostname} maps to ${routeName || "an unknown service"}; refusing to delete ambiguous DNS mapping`);
157
+ return;
158
+ }
159
+
160
+ assertOwnedResource(`Cloud Run service ${routeName}`, describeCloudRunService(routeName));
161
+ plan.hasProductionDomainMapping = true;
162
+ plan.resources.push({ label: `Production domain mapping ${config.domain.hostname}`, detail: `routes to ${routeName}` });
163
+ } catch (error) {
164
+ plan.blockers.push(`Production domain mapping ${config.domain.hostname}: ${formatError(error)}`);
106
165
  }
166
+ }
107
167
 
108
- run("gcx", ["resources", "delete", "--path", "./grafana", "--yes", "--on-error", "ignore"]);
109
- return "Grafana resources deleted from local manifests";
168
+ function planCloudRunServices(plan: DestroyPlan) {
169
+ try {
170
+ plan.serviceNames = listCloudRunServices().filter(matchesServiceResource);
171
+ if (plan.serviceNames.length === 0) {
172
+ plan.skipped.push({ label: `Cloud Run services in ${config.project.id}/${config.region}`, detail: "none matched" });
173
+ return;
174
+ }
175
+ for (const serviceName of plan.serviceNames) {
176
+ plan.resources.push({ label: `Cloud Run service ${serviceName}`, detail: `${config.project.id}/${config.region}` });
177
+ }
178
+ } catch (error) {
179
+ plan.blockers.push(`Cloud Run services in ${config.project.id}/${config.region}: ${formatError(error)}`);
180
+ }
181
+ }
182
+
183
+ function planSecrets(plan: DestroyPlan) {
184
+ try {
185
+ plan.secretNames = listSecrets().filter(matchesSecretResource);
186
+ if (plan.secretNames.length === 0) {
187
+ plan.skipped.push({ label: `Secret Manager secrets in ${config.project.id}`, detail: "none matched" });
188
+ return;
189
+ }
190
+ for (const secretName of plan.secretNames) {
191
+ plan.resources.push({ label: `Secret Manager secret ${secretName}`, detail: config.project.id });
192
+ }
193
+ } catch (error) {
194
+ plan.blockers.push(`Secret Manager secrets in ${config.project.id}: ${formatError(error)}`);
195
+ }
196
+ }
197
+
198
+ async function planNeon(plan: DestroyPlan) {
199
+ try {
200
+ const neon = await resolveNeonConfig();
201
+ const branches = await listBranches(neon.projectId);
202
+ const disposableBranches = branches.filter(
203
+ (branch: { name: string }) =>
204
+ branch.name.startsWith(`${neon.previewBranchPrefix}-`) || branch.name.startsWith(`${neon.personalBranchPrefix}-`)
205
+ );
206
+
207
+ plan.neon = {
208
+ projectId: neon.projectId,
209
+ baseBranchId: neon.baseBranchId,
210
+ databaseName: neon.databaseName,
211
+ branches: disposableBranches,
212
+ };
213
+ plan.resources.push({ label: `Neon database ${neon.databaseName}`, detail: `${neon.projectId}/${neon.baseBranchName}` });
214
+ for (const branch of disposableBranches) {
215
+ plan.resources.push({ label: `Neon branch ${branch.name}`, detail: neon.projectId });
216
+ }
217
+ } catch (error) {
218
+ plan.skipped.push({ label: "Neon resources", detail: formatError(error) });
219
+ }
110
220
  }
111
221
 
112
- function assertProductionDomainMappingOwned() {
113
- const mapping = describeProductionDomainMapping();
114
- if (!mapping) {
222
+ async function planGrafana(plan: DestroyPlan) {
223
+ if (!(await Bun.file("./grafana").exists())) {
224
+ plan.skipped.push({ label: "Grafana resources", detail: "no ./grafana directory" });
225
+ return;
226
+ }
227
+ if (!Bun.which("gcx")) {
228
+ plan.skipped.push({ label: "Grafana resources", detail: "gcx is not installed" });
115
229
  return;
116
230
  }
231
+ plan.resources.push({ label: "Grafana resources", detail: "./grafana manifests" });
232
+ }
233
+
234
+ function printDestroyPlan(plan: DestroyPlan) {
235
+ const lines = [
236
+ "Resources selected for destroy:",
237
+ ...plan.resources.map((resource) => `- ${resource.label}${resource.detail ? ` (${resource.detail})` : ""}`),
238
+ ];
239
+ if (plan.skipped.length > 0) {
240
+ lines.push("", "Skipped or not found:", ...plan.skipped.map((resource) => `- ${resource.label}${resource.detail ? ` (${resource.detail})` : ""}`));
241
+ }
242
+ if (plan.blockers.length > 0) {
243
+ lines.push("", "Discovery blockers:", ...plan.blockers.map((blocker) => `- ${blocker}`));
244
+ }
245
+ log.step(lines.join("\n"));
246
+ }
117
247
 
118
- const routeName = mapping.spec?.routeName;
119
- if (routeName !== config.serviceName) {
120
- throw new Error(`${config.domain.hostname} maps to ${routeName || "an unknown service"}; refusing to delete ambiguous DNS mapping`);
248
+ async function deleteGrafanaResources() {
249
+ if (!(await Bun.file("./grafana").exists())) {
250
+ return "No grafana directory configured";
251
+ }
252
+ if (!Bun.which("gcx")) {
253
+ return "gcx is not installed; Grafana resources were not deleted";
121
254
  }
122
255
 
123
- assertOwnedResource(`Cloud Run service ${routeName}`, describeCloudRunService(routeName));
256
+ run("gcx", ["resources", "delete", "--path", "./grafana", "--yes", "--on-error", "ignore"]);
257
+ return "Grafana resources deleted from local manifests";
124
258
  }
125
259
 
126
260
  async function requireDestroyConfirmation(force: boolean) {
@@ -161,7 +161,8 @@ export function ensureProject() {
161
161
  }
162
162
 
163
163
  export function attachBilling() {
164
- if (config.project.mode === "use_existing") {
164
+ const projectMode = config.project.mode as "create_new" | "use_existing";
165
+ if (projectMode === "use_existing") {
165
166
  return "Using existing project billing";
166
167
  }
167
168
  gcloud(["beta", "billing", "projects", "link", config.project.id, "--billing-account", config.project.billingAccount]);