diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 32ea43ca..fe756d50 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -68,6 +68,14 @@ import { serviceVersionShowCommand } from "./commands/service/version-show"; import { serviceVersionStartCommand } from "./commands/service/version-start"; import { serviceVersionStopCommand } from "./commands/service/version-stop"; import { skillsCommandFamily } from "./commands/skills/family"; +import { variableAddCommand } from "./commands/variable/add"; +import { variableDeleteCommand } from "./commands/variable/delete"; +import { variableGroupCreateCommand } from "./commands/variable/group-create"; +import { variableGroupDeleteCommand } from "./commands/variable/group-delete"; +import { variableGroupListCommand } from "./commands/variable/group-list"; +import { variableGroupUpdateCommand } from "./commands/variable/group-update"; +import { variableListCommand } from "./commands/variable/list"; +import { variableUpdateCommand } from "./commands/variable/update"; import { getCliVersion } from "./lib/version"; import { v7CommandFamily } from "./v7-redirects"; @@ -129,6 +137,14 @@ export const platformCommandFamily: CommandFamily = defineCommandFamily({ serviceDomainDelete: serviceDomainDeleteCommand, serviceDomainRetry: serviceDomainRetryCommand, serviceDomainWait: serviceDomainWaitCommand, + variableAdd: variableAddCommand, + variableUpdate: variableUpdateCommand, + variableDelete: variableDeleteCommand, + variableList: variableListCommand, + variableGroupList: variableGroupListCommand, + variableGroupCreate: variableGroupCreateCommand, + variableGroupUpdate: variableGroupUpdateCommand, + variableGroupDelete: variableGroupDeleteCommand, }, }); @@ -361,6 +377,32 @@ export const cliGroups: Readonly< description: "An emulator runs one kind of resource locally, so 'prisma dev' needs no account or network: one runs services, one runs Postgres databases, one runs S3-compatible buckets. Each holds instances, one per service, database or bucket that a 'prisma dev' started, from any directory on this machine. Emulators keep running after 'prisma dev' ends. Instances and their data stay until 'prisma dev --fresh' removes the current app's, and a stopped instance keeps its port.", }, + variable: { + brief: + "Manage project variables. Add, update, delete, and list values per group", + description: + "Variables live in groups: production, preview (shared by every branch that matches no custom rule), or a custom group. Values reach services when they deploy. Write commands require a group. For branch-level inspection, use --branch.", + workflow: [ + { + run: "variable add API_URL=https://api.example --group production", + brief: "Set a variable in the production group", + }, + { + run: "variable list --branch feature/foo", + brief: "See what a branch receives", + }, + { + run: "variable group create staging --equals staging", + brief: "Create a custom group for the staging branch", + }, + ], + }, + "variable group": { + brief: + "Manage variable groups. Create, rename, change rules, and delete custom groups", + description: + "Every project has a production group and a preview group. Add up to ten custom groups, each with an equals or startsWith rule that selects which branches receive its variables.", + }, skills: { brief: "Manage Prisma skills for AI coding agents. Sync and list the instruction files", @@ -426,6 +468,14 @@ export const mountedCommands: Readonly> = { "service domain delete": serviceDomainDeleteCommand, "service domain retry": serviceDomainRetryCommand, "service domain wait": serviceDomainWaitCommand, + "variable add": variableAddCommand, + "variable update": variableUpdateCommand, + "variable delete": variableDeleteCommand, + "variable list": variableListCommand, + "variable group list": variableGroupListCommand, + "variable group create": variableGroupCreateCommand, + "variable group update": variableGroupUpdateCommand, + "variable group delete": variableGroupDeleteCommand, // Composer's product verbs: deploy and dev at the root, their // children beneath them, and the local emulators under their own group. deploy: composerCommandFamily.commands.deploy, diff --git a/packages/cli/src/commands/branch/list.ts b/packages/cli/src/commands/branch/list.ts index a04a14d4..e25382f4 100644 --- a/packages/cli/src/commands/branch/list.ts +++ b/packages/cli/src/commands/branch/list.ts @@ -21,7 +21,7 @@ function listPresentations(result: BranchListResult): Presentations { const rows = result.branches.map((branch) => [ branch.name, branch.role, - branch.envMap, + branch.variableGroup, ]); return { json: () => result, @@ -43,7 +43,7 @@ function listPresentations(result: BranchListResult): Presentations { : [ { kind: "table" as const, - columns: ["Name", "Role", "Env map"], + columns: ["Name", "Role", "Variable group"], rows, }, ]), diff --git a/packages/cli/src/commands/project/env-add.ts b/packages/cli/src/commands/project/env-add.ts index 51914854..23bdce8a 100644 --- a/packages/cli/src/commands/project/env-add.ts +++ b/packages/cli/src/commands/project/env-add.ts @@ -87,6 +87,12 @@ export const projectEnvAddCommand = defineCommand({ }, needs: { credentials: true }, handler: async (args, ctx) => { + ctx.report({ + kind: "message", + severity: "warn", + text: "Warning: `prisma project env` is deprecated and will be removed in a future major version. Use `prisma variable` instead.", + }); + const source = resolveEnvWriteSource( args.positionals.assignment, args.flags.file, diff --git a/packages/cli/src/commands/project/env-delete.ts b/packages/cli/src/commands/project/env-delete.ts index 41340ff0..b43c3db7 100644 --- a/packages/cli/src/commands/project/env-delete.ts +++ b/packages/cli/src/commands/project/env-delete.ts @@ -72,6 +72,12 @@ export const projectEnvDeleteCommand = defineCommand({ }, needs: { credentials: true }, handler: async (args, ctx) => { + ctx.report({ + kind: "message", + severity: "warn", + text: "Warning: `prisma project env` is deprecated and will be removed in a future major version. Use `prisma variable` instead.", + }); + const key = args.positionals.key; const scope = requireEnvScope(args.flags, "delete"); const { projectId, resolved } = await resolveEnvTarget( diff --git a/packages/cli/src/commands/project/env-list.ts b/packages/cli/src/commands/project/env-list.ts index 3ea0c658..3e7dd22f 100644 --- a/packages/cli/src/commands/project/env-list.ts +++ b/packages/cli/src/commands/project/env-list.ts @@ -98,6 +98,12 @@ export const projectEnvListCommand = defineCommand({ }, needs: { credentials: true }, handler: async (args, ctx) => { + ctx.report({ + kind: "message", + severity: "warn", + text: "Warning: `prisma project env` is deprecated and will be removed in a future major version. Use `prisma variable` instead.", + }); + const explicit = resolveEnvScope( { roleName: args.flags.role, branchName: args.flags.branch }, { requireExplicit: false, command: "list" }, diff --git a/packages/cli/src/commands/project/env-update.ts b/packages/cli/src/commands/project/env-update.ts index 87662608..00939b2c 100644 --- a/packages/cli/src/commands/project/env-update.ts +++ b/packages/cli/src/commands/project/env-update.ts @@ -87,6 +87,12 @@ export const projectEnvUpdateCommand = defineCommand({ }, needs: { credentials: true }, handler: async (args, ctx) => { + ctx.report({ + kind: "message", + severity: "warn", + text: "Warning: `prisma project env` is deprecated and will be removed in a future major version. Use `prisma variable` instead.", + }); + const source = resolveEnvWriteSource( args.positionals.assignment, args.flags.file, diff --git a/packages/cli/src/commands/variable/add.ts b/packages/cli/src/commands/variable/add.ts new file mode 100644 index 00000000..85ad9246 --- /dev/null +++ b/packages/cli/src/commands/variable/add.ts @@ -0,0 +1,190 @@ +/** The `variable add` command. */ +import { + type Block, + defineCommand, + type Presentations, + positional, +} from "@prisma/cli-engine"; +import { ok } from "@prisma/cli-engine/protocol"; +import { parseKeyValuePositional } from "../../lib/app/env-config"; +import { readEnvFileAssignments } from "../../lib/app/env-file"; +import { createEnvVarInGroup } from "../../lib/variable/api"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { + branchFlag, + enforceRolePreviewCheck, + fileFlag, + groupFlag, + projectFlag, + rejectBranchWrite, + resolveGroupByTarget, + resolveGroupTarget, + roleFlag, + variableFieldRows, +} from "./shared"; + +function addPresentations(result: { + projectId: string; + groupName: string; + key: string; + id: string; + updatedAt: string; +}): Presentations { + return { + stdout: () => [result.id], + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Setting a new variable.", + }, + { + kind: "fields", + rows: variableFieldRows( + result.projectId, + result.groupName, + result.key, + result.id, + result.updatedAt, + ), + }, + ], + }; +} + +function addFilePresentations(result: { + projectId: string; + groupName: string; + keys: string[]; +}): Presentations { + return { + stdout: () => result.keys, + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Setting new variables from file.", + }, + { + kind: "fields", + rows: [ + { label: "project", value: result.projectId }, + { label: "group", value: result.groupName }, + ], + }, + result.keys.length === 0 + ? { kind: "summary", status: "info", text: "No variables imported." } + : { + kind: "table", + columns: ["key"], + rows: result.keys.map((k) => [k]), + }, + ], + }; +} + +export const variableAddCommand = defineCommand({ + args: { + positionals: { + assignment: positional.optionalString({ + brief: + "Variable assignment as KEY=VALUE, or KEY to read the value from the current environment", + placeholder: "assignment", + }), + }, + flags: { + group: groupFlag, + role: roleFlag, + file: fileFlag, + branch: branchFlag, + project: projectFlag, + }, + }, + help: { + summary: "Add a variable to a group", + description: + "Creates a branch variable in the named group: production, preview, or a custom group. Use --group or --role production|preview. The value comes from KEY=VALUE, from the current shell environment when only KEY is given, or from a dotenv file with --file. --branch is not accepted; use a variable group or send a service variable with the deploy.", + examples: [ + "variable add STRIPE_KEY=sk_test_xxx --group production", + "variable add STRIPE_KEY=sk_test_xxx --role production", + "variable add STRIPE_KEY=sk_test_xxx --group staging", + "variable add --file .env --group preview", + "API_URL=https://api.example prisma variable add API_URL --group production", + ], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + rejectBranchWrite(args.flags.branch, "add"); + + const target = resolveGroupTarget(args.flags.group, args.flags.role, "add"); + + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable add", + ); + const projectId = resolved.project.id; + + await enforceRolePreviewCheck(ctx.api, projectId, target, ctx.signal); + + const group = await resolveGroupByTarget( + ctx.api, + projectId, + target, + ctx.signal, + ); + + if (args.flags.file !== undefined) { + const assignments = await readEnvFileAssignments( + ctx.cwd, + args.flags.file, + "add", + ); + const keys: string[] = []; + for (const { key, value } of assignments) { + // biome-ignore lint/performance/noAwaitInLoops: keys are added one at a time so the import stops at the first failure. + await createEnvVarInGroup( + ctx.api, + { projectId, groupId: group.id, key, value }, + ctx.signal, + ); + keys.push(key); + } + return ok( + ctx.present( + { data: { projectId, groupName: group.name, keys } }, + addFilePresentations({ projectId, groupName: group.name, keys }), + ), + ); + } + + const { key, value } = parseKeyValuePositional( + args.positionals.assignment, + "add", + ctx.env, + ); + + const row = (await createEnvVarInGroup( + ctx.api, + { projectId, groupId: group.id, key, value }, + ctx.signal, + )) as { id: string; key: string; updatedAt: string }; + + const result = { + projectId, + groupName: group.name, + key: row.key, + id: row.id, + updatedAt: row.updatedAt, + }; + + return ok(ctx.present({ data: result }, addPresentations(result))); + }, +}); diff --git a/packages/cli/src/commands/variable/delete.ts b/packages/cli/src/commands/variable/delete.ts new file mode 100644 index 00000000..1821a489 --- /dev/null +++ b/packages/cli/src/commands/variable/delete.ts @@ -0,0 +1,156 @@ +/** The `variable delete` command. */ +import { + type Block, + defineCommand, + noDataLines, + type Presentations, + positional, +} from "@prisma/cli-engine"; +import { CliStructuredError, ok } from "@prisma/cli-engine/protocol"; +import { apiCallError } from "../../controllers/app-env-api"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { + branchFlag, + enforceRolePreviewCheck, + groupFlag, + projectFlag, + rejectBranchWrite, + resolveGroupByTarget, + resolveGroupTarget, + roleFlag, +} from "./shared"; + +function deletePresentations(result: { + projectId: string; + groupName: string; + key: string; +}): Presentations { + return { + stdout: noDataLines("A delete has no data; its exit code is the result."), + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Deleting the variable from the group.", + }, + { + kind: "fields", + rows: [ + { label: "project", value: result.projectId }, + { label: "group", value: result.groupName }, + { label: "key", value: result.key }, + ], + }, + ], + }; +} + +export const variableDeleteCommand = defineCommand({ + args: { + positionals: { + key: positional.string({ + brief: "Variable key to delete", + placeholder: "key", + }), + }, + flags: { + group: groupFlag, + role: roleFlag, + branch: branchFlag, + project: projectFlag, + }, + }, + help: { + summary: "Delete a variable from a group", + description: + "Removes the variable from the named group. The variable is gone from that group's deploys after the next deploy.", + examples: [ + "variable delete STRIPE_KEY --group production", + "variable delete STRIPE_KEY --role preview", + "variable delete STRIPE_KEY --group staging", + ], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + rejectBranchWrite(args.flags.branch, "delete"); + + const target = resolveGroupTarget( + args.flags.group, + args.flags.role, + "delete", + ); + + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable delete", + ); + const projectId = resolved.project.id; + + await enforceRolePreviewCheck(ctx.api, projectId, target, ctx.signal); + + const group = await resolveGroupByTarget( + ctx.api, + projectId, + target, + ctx.signal, + ); + + const key = args.positionals.key; + + // Look up the variable in this group. + const { + data: listData, + error: listError, + response: listResponse, + } = await ctx.api.GET("/v1/environment-variables", { + params: { + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + query: { projectId, key, groupId: group.id } as any, + }, + signal: ctx.signal, + }); + + if (listError || !listData) { + throw apiCallError(`Failed to look up ${key}`, listResponse, listError); + } + + const rows = listData.data as Array<{ id: string }>; + const existing = rows[0]; + + if (!existing) { + throw new CliStructuredError( + "VARIABLE.NOT_FOUND", + `Variable "${key}" not found in group "${group.name}"`, + { + why: "No variable with this key exists in the targeted group.", + nextActions: [ + { + kind: "user-choice", + label: `Run \`prisma variable list --group ${group.name}\` to see the available variables.`, + }, + ], + }, + ); + } + + const { error, response } = await ctx.api.DELETE( + "/v1/environment-variables/{envVarId}", + { + params: { path: { envVarId: existing.id } }, + signal: ctx.signal, + }, + ); + if (error) { + throw apiCallError(`Failed to delete ${key}`, response, error); + } + + const result = { projectId, groupName: group.name, key }; + return ok(ctx.present({ data: result }, deletePresentations(result))); + }, +}); diff --git a/packages/cli/src/commands/variable/group-create.ts b/packages/cli/src/commands/variable/group-create.ts new file mode 100644 index 00000000..66489bfc --- /dev/null +++ b/packages/cli/src/commands/variable/group-create.ts @@ -0,0 +1,146 @@ +/** The `variable group create` command. */ +import { + type Block, + defineCommand, + flag, + type Presentations, + positional, +} from "@prisma/cli-engine"; +import { CliStructuredError, ok } from "@prisma/cli-engine/protocol"; +import { createVariableGroup, formatGroupRule } from "../../lib/variable/api"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { projectFlag } from "./shared"; + +function createPresentations(result: { + projectId: string; + group: { id: string; name: string; class: string; rule: string }; +}): Presentations { + return { + stdout: () => [result.group.id], + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Variable group created.", + }, + { + kind: "fields", + rows: [ + { label: "project", value: result.projectId }, + { label: "name", value: result.group.name }, + { label: "class", value: result.group.class }, + { label: "rule", value: result.group.rule }, + { label: "id", value: result.group.id }, + ], + }, + ], + }; +} + +export const variableGroupCreateCommand = defineCommand({ + args: { + positionals: { + name: positional.string({ + brief: "Group name: lowercase letters, digits, and hyphens", + placeholder: "name", + }), + }, + flags: { + equals: flag.string({ + brief: + "Match branches whose git name equals this value exactly. Cannot be used with --starts-with", + placeholder: "branch-name", + }), + startsWith: flag.string({ + brief: + "Match branches whose git name starts with this prefix. Cannot be used with --equals", + placeholder: "prefix", + }), + project: projectFlag, + }, + }, + help: { + summary: "Create a custom variable group with a branch-matching rule", + description: + "Creates a new custom group for the project. Supply exactly one of --equals or --starts-with to define which branches receive this group's variables. Branches whose git name equals the value or starts with the prefix will source this group instead of the preview group.", + examples: [ + "variable group create staging --equals staging", + "variable group create features --starts-with feat/", + ], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + if ( + args.flags.equals !== undefined && + args.flags.startsWith !== undefined + ) { + throw new CliStructuredError( + "VARIABLE.GROUP_RULE_CONFLICT", + "variable group create accepts --equals or --starts-with, not both", + { + why: "A group has exactly one rule.", + nextActions: [ + { + kind: "user-choice", + label: "Pass --equals or --starts-with .", + }, + ], + }, + ); + } + + if ( + args.flags.equals === undefined && + args.flags.startsWith === undefined + ) { + throw new CliStructuredError( + "VARIABLE.GROUP_RULE_MISSING", + "variable group create requires --equals or --starts-with", + { + why: "Every custom group needs a rule so the platform knows which branches to route to it.", + nextActions: [ + { + kind: "user-choice", + label: "Pass --equals or --starts-with .", + }, + ], + }, + ); + } + + const rule = + args.flags.equals !== undefined + ? { type: "equals" as const, value: args.flags.equals } + : { type: "startsWith" as const, value: args.flags.startsWith ?? "" }; + + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable group create", + ); + const projectId = resolved.project.id; + + const group = await createVariableGroup( + ctx.api, + { projectId, name: args.positionals.name, rule }, + ctx.signal, + ); + + const data = { + projectId, + group: { + id: group.id, + name: group.name, + class: group.class, + rule: formatGroupRule(group), + }, + }; + + return ok(ctx.present({ data }, createPresentations(data))); + }, +}); diff --git a/packages/cli/src/commands/variable/group-delete.ts b/packages/cli/src/commands/variable/group-delete.ts new file mode 100644 index 00000000..aae23ade --- /dev/null +++ b/packages/cli/src/commands/variable/group-delete.ts @@ -0,0 +1,123 @@ +/** The `variable group delete` command. */ +import { + type Block, + defineCommand, + noDataLines, + type Presentations, + positional, +} from "@prisma/cli-engine"; +import { CliStructuredError, ok } from "@prisma/cli-engine/protocol"; +import { + deleteVariableGroup, + listVariableGroups, +} from "../../lib/variable/api"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { projectFlag } from "./shared"; + +function deletePresentations(result: { + projectId: string; + groupName: string; +}): Presentations { + return { + stdout: noDataLines("A delete has no data; its exit code is the result."), + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: `Variable group "${result.groupName}" and all its branch variables deleted.`, + }, + { + kind: "fields", + rows: [ + { label: "project", value: result.projectId }, + { label: "name", value: result.groupName }, + ], + }, + ], + }; +} + +export const variableGroupDeleteCommand = defineCommand({ + args: { + positionals: { + name: positional.string({ + brief: "Group name to delete", + placeholder: "name", + }), + }, + flags: { + project: projectFlag, + }, + }, + help: { + summary: "Delete a custom variable group and all its branch variables", + description: + "Permanently deletes the custom group and every variable in it. This cannot be undone. The confirmation token is the group name; pass it with --confirm to run non-interactively. Built-in groups (production, preview) cannot be deleted.", + examples: [ + "variable group delete staging", + "variable group delete staging --confirm staging", + ], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + const groupName = args.positionals.name; + + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable group delete", + ); + const projectId = resolved.project.id; + + const groups = await listVariableGroups(ctx.api, projectId, ctx.signal); + const existing = groups.find((g) => g.name === groupName); + + if (!existing) { + throw new CliStructuredError( + "VARIABLE.GROUP_NOT_FOUND", + `Variable group "${groupName}" not found`, + { + why: "No group with this name exists in the project.", + nextActions: [ + { + kind: "user-choice", + label: "Run `prisma variable group list` to see all groups.", + }, + ], + }, + ); + } + + if (existing.class !== "custom") { + throw new CliStructuredError( + "VARIABLE.BUILTIN_GROUP_DELETE", + `Built-in group "${groupName}" cannot be deleted`, + { + why: "The production and preview groups are created automatically and cannot be removed.", + nextActions: [ + { + kind: "user-choice", + label: + "Only custom groups can be deleted. Use `prisma variable group list` to list all groups.", + }, + ], + }, + ); + } + + await ctx.prompt.consent( + `Delete variable group "${groupName}" and all its branch variables?`, + { token: groupName }, + ); + + await deleteVariableGroup(ctx.api, existing.id, ctx.signal); + + const result = { projectId, groupName }; + return ok(ctx.present({ data: result }, deletePresentations(result))); + }, +}); diff --git a/packages/cli/src/commands/variable/group-list.ts b/packages/cli/src/commands/variable/group-list.ts new file mode 100644 index 00000000..cd173a4b --- /dev/null +++ b/packages/cli/src/commands/variable/group-list.ts @@ -0,0 +1,93 @@ +/** The `variable group list` command. */ +import { + type Block, + defineCommand, + type Presentations, +} from "@prisma/cli-engine"; +import { ok } from "@prisma/cli-engine/protocol"; +import { formatGroupRule, listVariableGroups } from "../../lib/variable/api"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { projectFlag } from "./shared"; + +function listPresentations(result: { + projectId: string; + groups: Array<{ + id: string; + name: string; + class: string; + rule: string; + matchedBranchIds: string[]; + }>; +}): Presentations { + const rows = result.groups.map((g) => [ + g.name, + g.class, + g.rule, + String(g.matchedBranchIds.length), + ]); + + return { + json: () => result, + next: () => [], + stdout: () => rows.map((row) => row.join("\t")), + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Listing variable groups.", + }, + { + kind: "fields", + rows: [{ label: "project", value: result.projectId }], + }, + rows.length === 0 + ? { kind: "summary", status: "info", text: "No variable groups found." } + : { + kind: "table", + columns: ["name", "class", "rule", "branches"], + rows, + }, + ], + }; +} + +export const variableGroupListCommand = defineCommand({ + args: { + flags: { + project: projectFlag, + }, + }, + help: { + summary: "List all variable groups for a project", + description: + "Shows the production and preview groups, then any custom groups ordered by name. Each row shows the group's name, class, matching rule, and how many branches it currently serves.", + examples: ["variable group list", "variable group list --project my-app"], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable group list", + ); + const projectId = resolved.project.id; + + const groups = await listVariableGroups(ctx.api, projectId, ctx.signal); + + const data = { + projectId, + groups: groups.map((g) => ({ + id: g.id, + name: g.name, + class: g.class, + rule: formatGroupRule(g), + matchedBranchIds: g.matchedBranchIds, + })), + }; + + return ok(ctx.present({ data }, listPresentations(data))); + }, +}); diff --git a/packages/cli/src/commands/variable/group-update.ts b/packages/cli/src/commands/variable/group-update.ts new file mode 100644 index 00000000..107204bd --- /dev/null +++ b/packages/cli/src/commands/variable/group-update.ts @@ -0,0 +1,220 @@ +/** The `variable group update` command. */ +import { + type Block, + defineCommand, + flag, + type Presentations, + positional, +} from "@prisma/cli-engine"; +import { CliStructuredError, ok } from "@prisma/cli-engine/protocol"; +import { + formatGroupRule, + listVariableGroups, + updateVariableGroup, +} from "../../lib/variable/api"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { projectFlag } from "./shared"; + +function updatePresentations(result: { + projectId: string; + group: { id: string; name: string; class: string; rule: string }; +}): Presentations { + return { + stdout: () => [result.group.id], + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Variable group updated.", + }, + { + kind: "fields", + rows: [ + { label: "project", value: result.projectId }, + { label: "name", value: result.group.name }, + { label: "class", value: result.group.class }, + { label: "rule", value: result.group.rule }, + { label: "id", value: result.group.id }, + ], + }, + ], + }; +} + +export const variableGroupUpdateCommand = defineCommand({ + args: { + positionals: { + currentName: positional.string({ + brief: "Current group name", + placeholder: "current-name", + }), + }, + flags: { + name: flag.string({ + brief: "New name for the group", + placeholder: "new-name", + }), + equals: flag.string({ + brief: "New equals rule; cannot be combined with --starts-with", + placeholder: "branch-name", + }), + startsWith: flag.string({ + brief: "New startsWith rule; cannot be combined with --equals", + placeholder: "prefix", + }), + project: projectFlag, + }, + }, + help: { + summary: "Rename a group or change its rule", + description: + "Updates a variable group: rename it with --name, replace its rule with --equals or --starts-with, or do both at once. Built-in groups (production, preview) accept --name only.", + examples: [ + "variable group update staging --name staging/eu", + "variable group update staging --equals staging-branch", + "variable group update features --starts-with feature/", + "variable group update staging --name staging/new --equals staging-new", + ], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + if ( + args.flags.equals !== undefined && + args.flags.startsWith !== undefined + ) { + throw new CliStructuredError( + "VARIABLE.GROUP_RULE_CONFLICT", + "variable group update accepts --equals or --starts-with, not both", + { + why: "A group has exactly one rule.", + nextActions: [ + { + kind: "user-choice", + label: "Pass --equals or --starts-with .", + }, + ], + }, + ); + } + + if ( + args.flags.name === undefined && + args.flags.equals === undefined && + args.flags.startsWith === undefined + ) { + throw new CliStructuredError( + "VARIABLE.GROUP_NOTHING_TO_UPDATE", + "variable group update requires at least one of --name, --equals, or --starts-with", + { + why: "Nothing to update.", + nextActions: [ + { + kind: "user-choice", + label: + "Pass --name to rename, or --equals/--starts-with to change the rule.", + }, + ], + }, + ); + } + + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable group update", + ); + const projectId = resolved.project.id; + + const groups = await listVariableGroups(ctx.api, projectId, ctx.signal); + const existing = groups.find( + (g) => g.name === args.positionals.currentName, + ); + + if (!existing) { + throw new CliStructuredError( + "VARIABLE.GROUP_NOT_FOUND", + `Variable group "${args.positionals.currentName}" not found`, + { + why: "No group with this name exists in the project.", + nextActions: [ + { + kind: "user-choice", + label: "Run `prisma variable group list` to see all groups.", + }, + ], + }, + ); + } + + const patch: { + name?: string; + rule?: { type: "equals" | "startsWith"; value: string } | null; + } = {}; + + if (args.flags.name !== undefined) { + patch.name = args.flags.name; + } + + if (args.flags.equals !== undefined) { + if (existing.class !== "custom") { + throw new CliStructuredError( + "VARIABLE.BUILTIN_GROUP_NO_RULE", + `Built-in group "${existing.name}" does not support rule changes`, + { + why: "Only custom groups have configurable rules.", + nextActions: [ + { + kind: "user-choice", + label: + "Create a custom group with `prisma variable group create`.", + }, + ], + }, + ); + } + patch.rule = { type: "equals", value: args.flags.equals }; + } else if (args.flags.startsWith !== undefined) { + if (existing.class !== "custom") { + throw new CliStructuredError( + "VARIABLE.BUILTIN_GROUP_NO_RULE", + `Built-in group "${existing.name}" does not support rule changes`, + { + why: "Only custom groups have configurable rules.", + nextActions: [ + { + kind: "user-choice", + label: + "Create a custom group with `prisma variable group create`.", + }, + ], + }, + ); + } + patch.rule = { type: "startsWith", value: args.flags.startsWith }; + } + + const updated = await updateVariableGroup( + ctx.api, + existing.id, + patch, + ctx.signal, + ); + + const data = { + projectId, + group: { + id: updated.id, + name: updated.name, + class: updated.class, + rule: formatGroupRule(updated), + }, + }; + + return ok(ctx.present({ data }, updatePresentations(data))); + }, +}); diff --git a/packages/cli/src/commands/variable/list.ts b/packages/cli/src/commands/variable/list.ts new file mode 100644 index 00000000..f9a11a54 --- /dev/null +++ b/packages/cli/src/commands/variable/list.ts @@ -0,0 +1,262 @@ +/** The `variable list` command. */ +import { + type Block, + defineCommand, + flag, + type Presentations, +} from "@prisma/cli-engine"; +import { ok } from "@prisma/cli-engine/protocol"; +import { listBranches } from "../../controllers/branch"; +import { + getResolvedVariables, + listEnvVarsInGroup, + listVariableGroups, + type RawVariableGroup, + type ResolvedVariableSource, +} from "../../lib/variable/api"; + +function sourceLabel(source: ResolvedVariableSource): string { + if (source.type === "group") { + return `group:${source.groupName}`; + } + if (source.type === "override") { + return "override"; + } + return `service:${source.serviceId}`; +} + +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { projectFlag, serviceFlag } from "./shared"; + +interface GroupWithVariables { + group: RawVariableGroup; + keys: string[]; +} + +function listPresentations(result: { + projectId: string; + groups?: GroupWithVariables[]; + branchResolved?: { + branchName: string; + groupName: string; + groupClass: string; + keys: Array<{ key: string; source: string }>; + }; +}): Presentations { + const branch = result.branchResolved; + if (branch) { + const rows = branch.keys.map((item) => [item.key, item.source]); + return { + json: () => result, + next: () => [], + stdout: () => rows.map((row) => row.join("\t")), + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: `Variables for branch ${branch.branchName}.`, + }, + { + kind: "fields", + rows: [ + { label: "project", value: result.projectId }, + { label: "branch", value: branch.branchName }, + { + label: "variable group", + value: `${branch.groupName} (${branch.groupClass})`, + }, + ], + }, + rows.length === 0 + ? { kind: "summary", status: "info", text: "No variables." } + : { + kind: "table", + columns: ["key", "source"], + rows, + }, + ], + }; + } + + const groups = result.groups ?? []; + const humanBlocks: Block[] = [ + { + kind: "summary", + status: "info", + text: "Listing variables by group.", + }, + { + kind: "fields", + rows: [{ label: "project", value: result.projectId }], + }, + ]; + + if (groups.length === 0) { + humanBlocks.push({ + kind: "summary", + status: "info", + text: "No variable groups found.", + }); + } else { + for (const { group, keys } of groups) { + humanBlocks.push({ + kind: "summary", + status: "info", + text: `Group: ${group.name} (${group.class})`, + } as Block); + if (keys.length === 0) { + humanBlocks.push({ + kind: "summary", + status: "info", + text: " No variables in this group.", + } as Block); + } else { + humanBlocks.push({ + kind: "table", + columns: ["key"], + rows: keys.map((k) => [k]), + } as Block); + } + } + } + + const stdoutRows: string[] = []; + for (const { group, keys } of groups) { + for (const key of keys) { + stdoutRows.push(`${group.name}\t${key}`); + } + } + + return { + json: () => result, + next: () => [], + stdout: () => stdoutRows, + human: () => humanBlocks, + }; +} + +export const variableListCommand = defineCommand({ + args: { + flags: { + group: flag.string({ + brief: "Show one group by name: production, preview, or a custom group", + placeholder: "name", + }), + branch: flag.string({ + brief: + "Show what one branch receives: its group and every key with its source", + placeholder: "git-name", + }), + service: serviceFlag, + project: projectFlag, + }, + }, + help: { + summary: "List branch variables by group, or what a branch receives", + description: + "Without flags, shows every group with its variable keys — one section per group. --group shows one group only. --branch shows the variable set a preview branch receives, including which group it sources and each key's origin. Add --service to include that service's variables too.", + examples: [ + "variable list", + "variable list --group production", + "variable list --group staging", + "variable list --branch feature/foo", + "variable list --branch feature/foo --service api", + ], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable list", + ); + const projectId = resolved.project.id; + + if (args.flags.branch !== undefined) { + // Resolve the branch to get its id. + const branches = await listBranches(ctx.api, projectId, ctx.signal); + const branch = branches.find((b) => b.gitName === args.flags.branch); + if (!branch) { + return ok( + ctx.present( + { + data: { + projectId, + branchResolved: { + branchName: args.flags.branch, + groupName: "unknown", + groupClass: "unknown", + keys: [], + }, + }, + }, + listPresentations({ + projectId, + branchResolved: { + branchName: args.flags.branch, + groupName: "unknown", + groupClass: "unknown", + keys: [], + }, + }), + ), + ); + } + + const resolvedVars = await getResolvedVariables(ctx.api, projectId, { + branchId: branch.id, + serviceId: args.flags.service, + signal: ctx.signal, + }); + + const keys = resolvedVars.data.map((item) => ({ + key: item.key, + source: sourceLabel(item.source), + })); + + const branchResolved = { + branchName: args.flags.branch, + groupName: resolvedVars.group.name, + groupClass: resolvedVars.group.class, + keys, + }; + + return ok( + ctx.present( + { data: { projectId, branchResolved } }, + listPresentations({ projectId, branchResolved }), + ), + ); + } + + // No --branch: show groups. + const allGroups = await listVariableGroups(ctx.api, projectId, ctx.signal); + + let targetGroups = allGroups; + if (args.flags.group !== undefined) { + const found = allGroups.find((g) => g.name === args.flags.group); + targetGroups = found ? [found] : []; + } + + const groupsWithVariables: GroupWithVariables[] = []; + for (const group of targetGroups) { + // biome-ignore lint/performance/noAwaitInLoops: sequential group fetches are acceptable for a list command. + const rows = (await listEnvVarsInGroup( + ctx.api, + projectId, + group.id, + ctx.signal, + )) as Array<{ key: string }>; + groupsWithVariables.push({ + group, + keys: rows.map((r) => r.key).sort(), + }); + } + + const data = { projectId, groups: groupsWithVariables }; + return ok(ctx.present({ data }, listPresentations(data))); + }, +}); diff --git a/packages/cli/src/commands/variable/shared.ts b/packages/cli/src/commands/variable/shared.ts new file mode 100644 index 00000000..34b3e4e9 --- /dev/null +++ b/packages/cli/src/commands/variable/shared.ts @@ -0,0 +1,203 @@ +/** Flags and utilities shared across the `prisma variable` commands. */ +import { flag } from "@prisma/cli-engine"; +import { CliStructuredError } from "@prisma/cli-engine/protocol"; +import type { ManagementApiClient } from "@prisma/management-api-sdk"; +import { + listVariableGroups, + type RawVariableGroup, +} from "../../lib/variable/api"; + +export const projectFlag = flag.string({ + brief: + "Project id or name (default: the project this directory is linked to)", + placeholder: "id-or-name", +}); + +export const groupFlag = flag.string({ + brief: + "Variable group name: production, preview, or a custom group. Cannot be used with --role", + placeholder: "name", +}); + +export const roleFlag = flag.enum({ + brief: + "Built-in group by role: production or preview. Cannot be used with --group", + values: ["production", "preview"], +}); + +export const fileFlag = flag.string({ + brief: + "Read KEY=VALUE assignments from a dotenv file; use to import many variables at once", + placeholder: "path", +}); + +export const branchFlag = flag.string({ + brief: "Branch git name", + placeholder: "git-name", +}); + +export const serviceFlag = flag.string({ + brief: "Service name or id", + placeholder: "id-or-name", +}); + +export type VariableGroupTarget = + | { kind: "group-name"; name: string } + | { kind: "role"; role: "production" | "preview" }; + +/** Resolve --group and --role into one target, enforcing mutual exclusion. */ +export function resolveGroupTarget( + groupName: string | undefined, + roleName: string | undefined, + command: "add" | "update" | "delete", +): VariableGroupTarget { + if (groupName !== undefined && roleName !== undefined) { + throw new CliStructuredError( + "VARIABLE.CONFLICTING_FLAGS", + `prisma variable ${command} accepts --group or --role, not both`, + { + why: "--group names any group including built-in ones; --role is a shorthand for production or preview.", + nextActions: [ + { + kind: "user-choice", + label: + "Pass --group production, --group preview, or --group .", + }, + ], + }, + ); + } + + if (groupName !== undefined) { + return { kind: "group-name", name: groupName }; + } + + if (roleName !== undefined) { + return { kind: "role", role: roleName as "production" | "preview" }; + } + + throw new CliStructuredError( + "VARIABLE.MISSING_GROUP", + `prisma variable ${command} requires --group or --role`, + { + why: "Writing without an explicit target is rejected so the command never silently targets production.", + nextActions: [ + { + kind: "user-choice", + label: + "Pass --role production, --role preview, or --group for a custom group.", + }, + ], + }, + ); +} + +/** Check if a project has any custom groups, and fail if --role preview was + * used in such a project (Decided 37: the strict --role preview check). */ +export async function enforceRolePreviewCheck( + client: ManagementApiClient, + projectId: string, + target: VariableGroupTarget, + signal: AbortSignal, +): Promise { + if (target.kind !== "role" || target.role !== "preview") { + return; + } + + const groups = await listVariableGroups(client, projectId, signal); + const hasCustomGroups = groups.some((g) => g.class === "custom"); + + if (hasCustomGroups) { + throw new CliStructuredError( + "VARIABLE.CUSTOM_GROUP_CONFLICT", + "This project has custom variable groups, so --role preview does not reach every preview branch", + { + why: "With custom groups, some preview branches receive a custom group instead of the preview group.", + nextActions: [ + { + kind: "user-choice", + label: + "Use --group preview for the preview group only, or --group for a specific custom group.", + }, + ], + }, + ); + } +} + +/** Resolve the group name to a RawVariableGroup object. */ +export async function resolveGroupByTarget( + client: ManagementApiClient, + projectId: string, + target: VariableGroupTarget, + signal: AbortSignal, +): Promise { + const groups = await listVariableGroups(client, projectId, signal); + + const name = target.kind === "role" ? target.role : target.name; + + const found = groups.find((g) => g.name === name); + if (!found) { + throw new CliStructuredError( + "VARIABLE.GROUP_NOT_FOUND", + `Variable group "${name}" not found in this project`, + { + why: "No group with this name exists.", + nextActions: [ + { + kind: "user-choice", + label: "Run prisma variable group list to see all groups.", + }, + ], + }, + ); + } + + return found; +} + +/** Shared error handler for --branch writes, which are not supported. */ +export function rejectBranchWrite( + branchName: string | undefined, + command: "add" | "update" | "delete", +): void { + if (branchName === undefined) { + return; + } + + throw new CliStructuredError( + "VARIABLE.NO_BRANCH_WRITE", + "`prisma variable` does not manage overrides", + { + why: "Overrides are being phased out. `prisma variable` sets branch variables in groups.", + nextActions: [ + { + kind: "user-choice", + label: + "Use `prisma project env` for existing overrides. For new values, set a branch variable in a group, or send a service variable with the deploy.", + }, + { + kind: "run-command", + label: `prisma project env ${command} KEY=value --branch ${branchName}`, + command: `prisma project env ${command} KEY=value --branch ${branchName}`, + }, + ], + }, + ); +} + +export function variableFieldRows( + projectId: string, + groupName: string, + key: string, + id: string, + updatedAt: string, +): Array<{ label: string; value: string }> { + return [ + { label: "project", value: projectId }, + { label: "group", value: groupName }, + { label: "key", value: key }, + { label: "id", value: id }, + { label: "last updated", value: updatedAt }, + ]; +} diff --git a/packages/cli/src/commands/variable/update.ts b/packages/cli/src/commands/variable/update.ts new file mode 100644 index 00000000..d72da099 --- /dev/null +++ b/packages/cli/src/commands/variable/update.ts @@ -0,0 +1,265 @@ +/** The `variable update` command. */ +import { + type Block, + defineCommand, + noDataLines, + type Presentations, + positional, +} from "@prisma/cli-engine"; +import { CliStructuredError, ok } from "@prisma/cli-engine/protocol"; +import type { ManagementApiClient } from "@prisma/management-api-sdk"; +import { apiCallError } from "../../controllers/app-env-api"; +import { parseKeyValuePositional } from "../../lib/app/env-config"; +import { readEnvFileAssignments } from "../../lib/app/env-file"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { + branchFlag, + enforceRolePreviewCheck, + fileFlag, + groupFlag, + projectFlag, + rejectBranchWrite, + resolveGroupByTarget, + resolveGroupTarget, + roleFlag, + variableFieldRows, +} from "./shared"; + +function updatePresentations(result: { + projectId: string; + groupName: string; + key: string; + id: string; + updatedAt: string; +}): Presentations { + return { + stdout: noDataLines( + "Replacing a value has no data; the variable keeps its key and id.", + ), + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Replacing the variable's value.", + }, + { + kind: "fields", + rows: variableFieldRows( + result.projectId, + result.groupName, + result.key, + result.id, + result.updatedAt, + ), + }, + ], + }; +} + +function updateFilePresentations(result: { + projectId: string; + groupName: string; + keys: string[]; +}): Presentations { + return { + stdout: noDataLines("Replacing values has no data output."), + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "summary", + status: "info", + text: "Replacing variable values from file.", + }, + { + kind: "fields", + rows: [ + { label: "project", value: result.projectId }, + { label: "group", value: result.groupName }, + ], + }, + result.keys.length === 0 + ? { kind: "summary", status: "info", text: "No variables updated." } + : { + kind: "table", + columns: ["key"], + rows: result.keys.map((k) => [k]), + }, + ], + }; +} + +export const variableUpdateCommand = defineCommand({ + args: { + positionals: { + assignment: positional.optionalString({ + brief: + "Variable assignment as KEY=VALUE, or KEY to read the value from the current environment", + placeholder: "assignment", + }), + }, + flags: { + group: groupFlag, + role: roleFlag, + file: fileFlag, + branch: branchFlag, + project: projectFlag, + }, + }, + help: { + summary: "Replace an existing variable's value in a group", + description: + "Replaces one variable's value in the named group; the variable must already exist (use `prisma variable add` to create it). With --file, replaces every variable the dotenv file lists.", + examples: [ + "variable update STRIPE_KEY=sk_new_xxx --group production", + "variable update STRIPE_KEY=sk_new_xxx --role preview", + "variable update --file .env --group staging", + ], + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + rejectBranchWrite(args.flags.branch, "update"); + + const target = resolveGroupTarget( + args.flags.group, + args.flags.role, + "update", + ); + + const workspace = await resolveActiveWorkspace(ctx); + const resolved = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "variable update", + ); + const projectId = resolved.project.id; + + await enforceRolePreviewCheck(ctx.api, projectId, target, ctx.signal); + + const group = await resolveGroupByTarget( + ctx.api, + projectId, + target, + ctx.signal, + ); + + if (args.flags.file !== undefined) { + const assignments = await readEnvFileAssignments( + ctx.cwd, + args.flags.file, + "update", + ); + const keys: string[] = []; + for (const { key, value } of assignments) { + // biome-ignore lint/performance/noAwaitInLoops: keys are updated one at a time so the import stops at the first failure. + const updated = await updateValueInGroup( + ctx.api, + { projectId, groupId: group.id, key, value }, + ctx.signal, + ); + if (updated) { + keys.push(key); + } + } + return ok( + ctx.present( + { data: { projectId, groupName: group.name, keys } }, + updateFilePresentations({ projectId, groupName: group.name, keys }), + ), + ); + } + + const { key, value } = parseKeyValuePositional( + args.positionals.assignment, + "update", + ctx.env, + ); + + const updated = await updateValueInGroup( + ctx.api, + { projectId, groupId: group.id, key, value }, + ctx.signal, + ); + + if (!updated) { + throw new CliStructuredError( + "VARIABLE.NOT_FOUND", + `Variable "${key}" not found in group "${group.name}"`, + { + why: "No variable with this key exists in the targeted group.", + nextActions: [ + { + kind: "user-choice", + label: `Use \`prisma variable add ${key}= --group ${group.name}\` to create it.`, + }, + ], + }, + ); + } + + const result = { + projectId, + groupName: group.name, + key: updated.key, + id: updated.id, + updatedAt: updated.updatedAt, + }; + + return ok(ctx.present({ data: result }, updatePresentations(result))); + }, +}); + +/** Replaces the value of `key` in one variable group. Returns null when the group has no such key. */ +async function updateValueInGroup( + api: ManagementApiClient, + input: { projectId: string; groupId: string; key: string; value: string }, + signal: AbortSignal, +): Promise<{ id: string; key: string; updatedAt: string } | null> { + const query = { + projectId: input.projectId, + key: input.key, + groupId: input.groupId, + }; + const { + data: listData, + error: listError, + response: listResponse, + } = await api.GET("/v1/environment-variables", { + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + params: { query: query as any }, + signal, + }); + if (listError || !listData) { + throw apiCallError( + `Failed to look up ${input.key}`, + listResponse, + listError, + ); + } + + const existing = (listData.data as Array<{ id: string }>)[0]; + if (!existing) { + return null; + } + + const { data, error, response } = await api.PATCH( + "/v1/environment-variables/{envVarId}", + { + params: { path: { envVarId: existing.id } }, + body: { value: input.value }, + signal, + }, + ); + if (error || !data) { + throw apiCallError( + `Failed to update value for ${input.key}`, + response, + error, + ); + } + return data.data as { id: string; key: string; updatedAt: string }; +} diff --git a/packages/cli/src/controllers/branch.ts b/packages/cli/src/controllers/branch.ts index 679d15b2..345716c0 100644 --- a/packages/cli/src/controllers/branch.ts +++ b/packages/cli/src/controllers/branch.ts @@ -6,6 +6,7 @@ export interface RawBranchRecord { id: string; gitName: string; role: BranchRole; + variableGroup?: { id: string; name: string; class: string } | null; } export function sortBranches(branches: BranchSummary[]): BranchSummary[] { @@ -39,5 +40,6 @@ export function toBranchSummary(branch: RawBranchRecord): BranchSummary { name: branch.gitName, role: branch.role, envMap: branch.role, + variableGroup: branch.variableGroup?.name ?? branch.role, }; } diff --git a/packages/cli/src/lib/branch/list.ts b/packages/cli/src/lib/branch/list.ts index 5443c7e6..aaf6b37f 100644 --- a/packages/cli/src/lib/branch/list.ts +++ b/packages/cli/src/lib/branch/list.ts @@ -2,11 +2,18 @@ import { CliStructuredError } from "@prisma/cli-engine/protocol"; import type { ManagementApiClient } from "@prisma/management-api-sdk"; import type { BranchRole } from "../../types/branch"; +export interface BranchVariableGroup { + readonly id: string; + readonly name: string; + readonly class: string; +} + export interface BranchRecord { readonly id: string; readonly gitName: string; readonly isDefault: boolean; readonly role: BranchRole; + readonly variableGroup?: BranchVariableGroup | null; } /** Every live Branch of a Project, following the cursor through each @@ -47,6 +54,9 @@ export async function listProjectBranches( gitName: branch.gitName, isDefault: branch.isDefault, role: branch.role, + variableGroup: + (branch as { variableGroup?: BranchVariableGroup | null }) + .variableGroup ?? null, })), ); cursor = data.pagination.hasMore diff --git a/packages/cli/src/lib/variable/api.ts b/packages/cli/src/lib/variable/api.ts new file mode 100644 index 00000000..992b1ac1 --- /dev/null +++ b/packages/cli/src/lib/variable/api.ts @@ -0,0 +1,329 @@ +// biome-ignore-all lint/performance/noAwaitInLoops: Variable list pagination requests must run sequentially. +/** Typed wrappers for variable-group endpoints not yet in the published SDK. + * + * The @prisma/management-api-sdk v1.80.0 predates these endpoints. + * Rather than cast at every call site, this module holds one typed + * boundary: local interfaces match the OpenAPI contract, and each + * function casts once to call the raw client. + */ +import { CliStructuredError } from "@prisma/cli-engine/protocol"; +import type { ManagementApiClient } from "@prisma/management-api-sdk"; +import { runCommand, userChoice } from "../app/env-errors"; + +// --------------------------------------------------------------------------- +// Local types that mirror the OpenAPI shapes +// --------------------------------------------------------------------------- + +export type VariableGroupClass = "production" | "preview" | "custom"; +export type VariableGroupRule = "equals" | "startsWith"; + +export interface RawVariableGroup { + id: string; + type: "variable-group"; + url: string; + projectId: string; + name: string; + class: VariableGroupClass; + rule: VariableGroupRule | null; + ruleValue: string | null; + matchedBranchIds: string[]; + createdAt: string; + updatedAt: string; +} + +export type ResolvedVariableSource = + | { + type: "group"; + groupId: string; + groupName: string; + groupClass: VariableGroupClass; + } + | { type: "service"; serviceId: string } + | { type: "override" }; + +export interface ResolvedVariable { + key: string; + updatedAt: string; + isManagedBySystem: boolean; + source: ResolvedVariableSource; +} + +export interface ResolvedVariablesResult { + group: { id: string; name: string; class: VariableGroupClass }; + data: ResolvedVariable[]; +} + +interface ApiErrorBody { + error?: { + code?: string; + message?: string; + hint?: string; + }; +} + +function variableApiError( + summary: string, + response: Response | undefined, + error: ApiErrorBody | undefined, +): CliStructuredError { + const status = response?.status ?? 0; + const apiCode = error?.error?.code; + const apiMessage = error?.error?.message; + const apiHint = error?.error?.hint; + + if (status === 401 || status === 403) { + return new CliStructuredError("VARIABLE.API_ERROR", summary, { + why: "The Management API rejected the request as unauthorized or forbidden.", + meta: { status }, + nextActions: [runCommand("prisma auth login")], + }); + } + + return new CliStructuredError("VARIABLE.API_ERROR", summary, { + why: + apiMessage ?? + `The Management API returned status ${status || "unknown"}.`, + ...(status || apiCode !== undefined + ? { + meta: { + ...(status ? { status } : {}), + ...(apiCode !== undefined ? { apiCode } : {}), + }, + } + : {}), + nextActions: [ + userChoice( + apiHint ?? + "Re-run with --log-level verbose for the underlying API response details.", + ), + ], + }); +} + +// --------------------------------------------------------------------------- +// Variable group API calls +// --------------------------------------------------------------------------- + +/** List all variable groups for a project. */ +export async function listVariableGroups( + client: ManagementApiClient, + projectId: string, + signal: AbortSignal, +): Promise { + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + const { data, error, response } = await (client as any).GET( + "/v1/variable-groups", + { + params: { query: { projectId } }, + signal, + }, + ); + if (error || !data) { + throw variableApiError("Failed to list variable groups", response, error); + } + return (data.data as RawVariableGroup[]) ?? []; +} + +/** Create a custom variable group. */ +export async function createVariableGroup( + client: ManagementApiClient, + input: { + projectId: string; + name: string; + rule: { type: "equals" | "startsWith"; value: string }; + }, + signal: AbortSignal, +): Promise { + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + const { data, error, response } = await (client as any).POST( + "/v1/variable-groups", + { + body: { projectId: input.projectId, name: input.name, rule: input.rule }, + signal, + }, + ); + if (error || !data) { + throw variableApiError("Failed to create variable group", response, error); + } + return data.data as RawVariableGroup; +} + +/** Update a variable group's name and/or rule. */ +export async function updateVariableGroup( + client: ManagementApiClient, + groupId: string, + patch: { + name?: string; + rule?: { type: "equals" | "startsWith"; value: string } | null; + }, + signal: AbortSignal, +): Promise { + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + const { data, error, response } = await (client as any).PATCH( + "/v1/variable-groups/{groupId}", + { + params: { path: { groupId } }, + body: patch, + signal, + }, + ); + if (error || !data) { + throw variableApiError("Failed to update variable group", response, error); + } + return data.data as RawVariableGroup; +} + +// --------------------------------------------------------------------------- +// Presentation helpers +// --------------------------------------------------------------------------- + +/** Format a group's rule for display. */ +export function formatGroupRule(group: RawVariableGroup): string { + if (group.class === "production") { + return "production branch"; + } + if (group.class === "preview") { + return "all other branches"; + } + if (group.rule === "equals") { + return `= ${group.ruleValue}`; + } + if (group.rule === "startsWith") { + return `starts-with ${group.ruleValue}`; + } + return ""; +} + +/** Delete a custom variable group and all its variables. */ +export async function deleteVariableGroup( + client: ManagementApiClient, + groupId: string, + signal: AbortSignal, +): Promise { + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + const { error, response } = await (client as any).DELETE( + "/v1/variable-groups/{groupId}", + { + params: { path: { groupId } }, + signal, + }, + ); + if (error) { + throw variableApiError("Failed to delete variable group", response, error); + } +} + +// --------------------------------------------------------------------------- +// Resolved variables +// --------------------------------------------------------------------------- + +/** Get the resolved variable set a branch receives at deploy time. */ +export async function getResolvedVariables( + client: ManagementApiClient, + projectId: string, + options: { + branchId?: string; + serviceId?: string; + signal: AbortSignal; + }, +): Promise { + const query: Record = {}; + if (options.branchId !== undefined) { + query.branchId = options.branchId; + } + if (options.serviceId !== undefined) { + query.serviceId = options.serviceId; + } + + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + const { data, error, response } = await (client as any).GET( + "/v1/projects/{projectId}/resolved-variables", + { + params: { path: { projectId }, query }, + signal: options.signal, + }, + ); + if (error || !data) { + throw variableApiError("Failed to get resolved variables", response, error); + } + return data as ResolvedVariablesResult; +} + +// --------------------------------------------------------------------------- +// Env var creation with groupId +// --------------------------------------------------------------------------- + +export interface CreateEnvVarWithGroupInput { + projectId: string; + key: string; + value: string; + groupId: string; +} + +/** Create an env var in a named group. */ +export async function createEnvVarInGroup( + client: ManagementApiClient, + input: CreateEnvVarWithGroupInput, + signal: AbortSignal, +): Promise { + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + const { data, error, response } = await (client as any).POST( + "/v1/environment-variables", + { + body: { + projectId: input.projectId, + groupId: input.groupId, + key: input.key, + value: input.value, + }, + signal, + }, + ); + if (error || !data) { + throw variableApiError(`Failed to add ${input.key}`, response, error); + } + return data.data; +} + +/** List env vars in one group by groupId. */ +export async function listEnvVarsInGroup( + client: ManagementApiClient, + projectId: string, + groupId: string, + signal: AbortSignal, +): Promise { + const collected: unknown[] = []; + let cursor: string | undefined; + + while (true) { + const query: Record = { projectId, groupId }; + if (cursor !== undefined) { + query.cursor = cursor; + } + + // biome-ignore lint/suspicious/noExplicitAny: these API paths and fields are not in the published SDK yet + const { data, error, response } = await (client as any).GET( + "/v1/environment-variables", + { + params: { query }, + signal, + }, + ); + if (error || !data) { + throw variableApiError( + "Failed to list variables for group", + response, + error, + ); + } + + collected.push(...(data.data as unknown[])); + + if (!data.pagination.hasMore || !data.pagination.nextCursor) { + break; + } + cursor = data.pagination.nextCursor; + } + + return collected; +} diff --git a/packages/cli/src/types/branch.ts b/packages/cli/src/types/branch.ts index 408d3173..5bff79bc 100644 --- a/packages/cli/src/types/branch.ts +++ b/packages/cli/src/types/branch.ts @@ -4,11 +4,19 @@ import type { ProjectResolution, ProjectSummary } from "./project"; export type BranchRole = "preview" | "production"; export type BranchKind = BranchRole; +export interface BranchVariableGroup { + id: string; + name: string; + class: string; +} + export interface BranchSummary { id: string; name: string; role: BranchRole; + /** @deprecated Use variableGroup.name instead. */ envMap: BranchRole; + variableGroup: string; } export interface BranchListResult { diff --git a/packages/cli/tests/branch.test.ts b/packages/cli/tests/branch.test.ts index cccfd39c..b82a2de6 100644 --- a/packages/cli/tests/branch.test.ts +++ b/packages/cli/tests/branch.test.ts @@ -147,7 +147,7 @@ describe("prisma branch list", () => { { kind: "fields", rows: [{ label: "project", value: "Billing" }] }, { kind: "table", - columns: ["Name", "Role", "Env map"], + columns: ["Name", "Role", "Variable group"], rows: [ ["main", "production", "production"], ["alpha", "preview", "preview"], diff --git a/packages/cli/tests/e2e-coverage.test.ts b/packages/cli/tests/e2e-coverage.test.ts index 71dbb08d..ce14d02e 100644 --- a/packages/cli/tests/e2e-coverage.test.ts +++ b/packages/cli/tests/e2e-coverage.test.ts @@ -111,6 +111,22 @@ const EXCLUSIONS: Readonly> = { "dev url": LOCAL_EMULATOR_REASON, "dev stop": LOCAL_EMULATOR_REASON, "emulator list": LOCAL_EMULATOR_REASON, + "variable add": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", + "variable update": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", + "variable delete": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", + "variable list": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", + "variable group list": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", + "variable group create": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", + "variable group update": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", + "variable group delete": + "Variable group endpoints are not yet in the published @prisma/management-api-sdk. End-to-end tests require the demo control-plane deployment that ships with pdp-control-plane#6109.", }; /** diff --git a/packages/cli/tests/mount-coverage.test.ts b/packages/cli/tests/mount-coverage.test.ts index cceb3de7..70225448 100644 --- a/packages/cli/tests/mount-coverage.test.ts +++ b/packages/cli/tests/mount-coverage.test.ts @@ -166,6 +166,14 @@ const EXPECTED_MOUNT_PATHS: readonly string[] = [ "telemetry disable", "telemetry enable", "telemetry status", + "variable add", + "variable delete", + "variable group create", + "variable group delete", + "variable group list", + "variable group update", + "variable list", + "variable update", ]; const MOUNTED_FAMILIES = { diff --git a/packages/cli/tests/variable.test.ts b/packages/cli/tests/variable.test.ts new file mode 100644 index 00000000..75cb48d0 --- /dev/null +++ b/packages/cli/tests/variable.test.ts @@ -0,0 +1,857 @@ +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { ManagementApiClient, StreamEvent } from "@prisma/cli-engine"; +import { createTestCli, mintTestJwt } from "@prisma/cli-engine/testing"; +import { describe, expect, it } from "vitest"; + +import { variableAddCommand } from "../src/commands/variable/add"; +import { variableDeleteCommand } from "../src/commands/variable/delete"; +import { variableGroupCreateCommand } from "../src/commands/variable/group-create"; +import { variableGroupDeleteCommand } from "../src/commands/variable/group-delete"; +import { variableGroupListCommand } from "../src/commands/variable/group-list"; +import { variableListCommand } from "../src/commands/variable/list"; +import { variableUpdateCommand } from "../src/commands/variable/update"; + +const ACME_SESSION = { + workspaceId: "ws_1", + workspaceName: "Acme Inc", + credential: { + token: mintTestJwt({ sub: "usr_1", workspace_id: "ws_1" }), + refreshToken: undefined, + expiresAt: undefined, + }, +}; + +const PROJECTS = [ + { + id: "proj_1", + name: "Billing", + workspace: { id: "wksp_ws_1", name: "Acme Inc" }, + }, +]; + +const PRODUCTION_GROUP = { + id: "vg_prod", + type: "variable-group", + url: "https://api.prisma.io/v1/variable-groups/vg_prod", + projectId: "proj_1", + name: "production", + class: "production", + rule: null, + ruleValue: null, + matchedBranchIds: ["br_main"], + createdAt: "2024-01-01T00:00:00Z", + updatedAt: "2024-01-01T00:00:00Z", +}; + +const PREVIEW_GROUP = { + id: "vg_prev", + type: "variable-group", + url: "https://api.prisma.io/v1/variable-groups/vg_prev", + projectId: "proj_1", + name: "preview", + class: "preview", + rule: null, + ruleValue: null, + matchedBranchIds: ["br_1"], + createdAt: "2024-01-01T00:00:00Z", + updatedAt: "2024-01-01T00:00:00Z", +}; + +const CUSTOM_GROUP = { + id: "vg_custom", + type: "variable-group", + url: "https://api.prisma.io/v1/variable-groups/vg_custom", + projectId: "proj_1", + name: "staging", + class: "custom", + rule: "equals", + ruleValue: "staging", + matchedBranchIds: ["br_staging"], + createdAt: "2024-01-01T00:00:00Z", + updatedAt: "2024-01-01T00:00:00Z", +}; + +const BUILT_IN_GROUPS = [PRODUCTION_GROUP, PREVIEW_GROUP]; +const ALL_GROUPS = [PRODUCTION_GROUP, PREVIEW_GROUP, CUSTOM_GROUP]; + +interface Call { + readonly method: string; + readonly path: string; + readonly init: { + params?: { path?: Record; query?: Record }; + body?: unknown; + }; +} + +type Responder = (call: Call) => unknown; + +interface VariableClientSpec { + readonly groups?: unknown[]; + readonly calls?: Call[]; + readonly routes?: Readonly>; +} + +function variableClient(spec: VariableClientSpec = {}): ManagementApiClient { + const page = { hasMore: false, nextCursor: null }; + + // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: one fake answers every endpoint these tests call. + const dispatch = (method: string, apiPath: string, init: Call["init"]) => { + const call: Call = { method, path: apiPath, init: init ?? {} }; + spec.calls?.push(call); + const route = spec.routes?.[`${method} ${apiPath}`]; + if (route) { + return route(call); + } + + if (method === "GET" && apiPath === "/v1/projects") { + return { data: { data: PROJECTS } }; + } + if (method === "GET" && apiPath === "/v1/variable-groups") { + return { data: { data: spec.groups ?? BUILT_IN_GROUPS } }; + } + if (method === "GET" && apiPath === "/v1/environment-variables") { + return { data: { data: [], pagination: page } }; + } + if (method === "POST" && apiPath === "/v1/environment-variables") { + const body = init.body as Record; + return { + data: { + data: { + id: "ev_new", + key: body.key, + updatedAt: "2024-06-01T00:00:00Z", + }, + }, + }; + } + if (method === "POST" && apiPath === "/v1/variable-groups") { + const body = init.body as Record; + return { + data: { + data: { + id: "vg_new", + type: "variable-group", + url: "https://api.prisma.io/v1/variable-groups/vg_new", + projectId: body.projectId, + name: body.name, + class: "custom", + rule: (body.rule as { type: string }).type, + ruleValue: (body.rule as { value: string }).value, + matchedBranchIds: [], + createdAt: "2024-06-01T00:00:00Z", + updatedAt: "2024-06-01T00:00:00Z", + }, + }, + }; + } + return { data: { data: {} } }; + }; + + return { + GET: async (apiPath: string, init: Call["init"]) => + dispatch("GET", apiPath, init), + POST: async (apiPath: string, init: Call["init"]) => + dispatch("POST", apiPath, init), + PATCH: async (apiPath: string, init: Call["init"]) => + dispatch("PATCH", apiPath, init), + DELETE: async (apiPath: string, init: Call["init"]) => + dispatch("DELETE", apiPath, init), + } as unknown as ManagementApiClient; +} + +function makeCli( + client: ManagementApiClient, + commands: Record = {}, +) { + return createTestCli({ + commands: { + "variable add": variableAddCommand, + "variable update": variableUpdateCommand, + "variable delete": variableDeleteCommand, + "variable list": variableListCommand, + "variable group list": variableGroupListCommand, + "variable group create": variableGroupCreateCommand, + "variable group delete": variableGroupDeleteCommand, + ...commands, + }, + groups: { + variable: { brief: "Manage project variables" }, + "variable group": { brief: "Manage variable groups" }, + }, + sessions: [ACME_SESSION], + selectedWorkspaceId: ACME_SESSION.workspaceId, + managementApi: { client }, + now: () => new Date(0), + }); +} + +async function pinnedCwd() { + const cwd = await mkdtemp(path.join(os.tmpdir(), "variable-test-")); + await mkdir(path.join(cwd, ".prisma"), { recursive: true }); + await writeFile( + path.join(cwd, ".prisma", "local.json"), + `${JSON.stringify({ workspaceId: "ws_1", projectId: "proj_1" }, null, 2)}\n`, + "utf8", + ); + return cwd; +} + +function resultFrame(frames: ReadonlyArray<{ kind: string }>) { + const frame = frames.at(-1); + if (frame === undefined || frame.kind !== "result") { + throw new Error("expected a terminal result frame"); + } + return frame as Extract; +} + +// --------------------------------------------------------------------------- +// Flag validation +// --------------------------------------------------------------------------- + +describe("flag validation", () => { + it("rejects --group and --role used together", async () => { + const result = await makeCli(variableClient()).run( + [ + "variable", + "add", + "KEY=val", + "--group", + "production", + "--role", + "preview", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.CONFLICTING_FLAGS" }, + }); + }); + + it("rejects add without --group or --role", async () => { + const result = await makeCli(variableClient()).run( + ["variable", "add", "KEY=val", "--json"], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.MISSING_GROUP" }, + }); + }); + + it("rejects --branch on variable add", async () => { + const result = await makeCli(variableClient()).run( + [ + "variable", + "add", + "KEY=val", + "--branch", + "feature/foo", + "--group", + "production", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.NO_BRANCH_WRITE" }, + }); + }); + + it("rejects --branch on variable update", async () => { + const result = await makeCli(variableClient()).run( + [ + "variable", + "update", + "KEY=val", + "--branch", + "feature/foo", + "--group", + "production", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.NO_BRANCH_WRITE" }, + }); + }); + + it("rejects --branch on variable delete", async () => { + const result = await makeCli(variableClient()).run( + [ + "variable", + "delete", + "KEY", + "--branch", + "feature/foo", + "--group", + "production", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.NO_BRANCH_WRITE" }, + }); + }); +}); + +// --------------------------------------------------------------------------- +// Strict preview check +// --------------------------------------------------------------------------- + +describe("strict --role preview check", () => { + it("fails when the project has custom groups", async () => { + const result = await makeCli(variableClient({ groups: ALL_GROUPS })).run( + ["variable", "add", "KEY=val", "--role", "preview", "--json"], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.CUSTOM_GROUP_CONFLICT" }, + }); + }); + + it("allows --role preview when there are no custom groups", async () => { + const result = await makeCli( + variableClient({ groups: BUILT_IN_GROUPS }), + ).run(["variable", "add", "KEY=val", "--role", "preview", "--json"], { + cwd: await pinnedCwd(), + }); + + expect(result.exitCode).toBe(0); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: true, + }); + }); +}); + +// --------------------------------------------------------------------------- +// variable add +// --------------------------------------------------------------------------- + +describe("variable add", () => { + it("POSTs to /v1/environment-variables with the group's id", async () => { + const calls: Call[] = []; + const result = await makeCli(variableClient({ calls })).run( + [ + "variable", + "add", + "STRIPE_KEY=sk_test_xxx", + "--group", + "production", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(0); + + const post = calls.find( + (c) => c.method === "POST" && c.path === "/v1/environment-variables", + ); + expect(post?.init.body).toMatchObject({ + projectId: "proj_1", + groupId: "vg_prod", + key: "STRIPE_KEY", + value: "sk_test_xxx", + }); + }); + + it("resolves --role production to the production group id", async () => { + const calls: Call[] = []; + await makeCli(variableClient({ calls })).run( + ["variable", "add", "KEY=val", "--role", "production"], + { cwd: await pinnedCwd() }, + ); + + const post = calls.find( + (c) => c.method === "POST" && c.path === "/v1/environment-variables", + ); + expect(post?.init.body).toMatchObject({ groupId: "vg_prod" }); + }); + + it("fails when the group name does not exist", async () => { + const result = await makeCli(variableClient()).run( + ["variable", "add", "KEY=val", "--group", "nonexistent", "--json"], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.GROUP_NOT_FOUND" }, + }); + }); + + it("imports all variables from a dotenv file", async () => { + const cwd = await pinnedCwd(); + await writeFile(path.join(cwd, ".env"), "A=1\nB=2\n", "utf8"); + + const calls: Call[] = []; + const result = await makeCli(variableClient({ calls })).run( + ["variable", "add", "--file", ".env", "--group", "production", "--json"], + { cwd }, + ); + + expect(result.exitCode).toBe(0); + const posts = calls.filter( + (c) => c.method === "POST" && c.path === "/v1/environment-variables", + ); + expect(posts).toHaveLength(2); + const keys = posts.map((c) => (c.init.body as { key: string }).key).sort(); + expect(keys).toEqual(["A", "B"]); + }); +}); + +// --------------------------------------------------------------------------- +// variable update +// --------------------------------------------------------------------------- + +describe("variable update", () => { + it("PATCHes the matching variable by id", async () => { + const existingVar = { + id: "ev_existing", + key: "API_KEY", + groupId: "vg_prod", + updatedAt: "2024-01-01T00:00:00Z", + }; + + const calls: Call[] = []; + const result = await makeCli( + variableClient({ + calls, + routes: { + "GET /v1/environment-variables": () => ({ + data: { + data: [existingVar], + pagination: { hasMore: false, nextCursor: null }, + }, + }), + "PATCH /v1/environment-variables/{envVarId}": (call) => ({ + data: { + data: { + id: "ev_existing", + key: "API_KEY", + updatedAt: "2024-06-01T00:00:00Z", + ...(call.init.body as object), + }, + }, + }), + }, + }), + ).run( + [ + "variable", + "update", + "API_KEY=new_value", + "--group", + "production", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(0); + + const patch = calls.find( + (c) => + c.method === "PATCH" && + c.path === "/v1/environment-variables/{envVarId}", + ); + expect(patch?.init.params?.path).toMatchObject({ envVarId: "ev_existing" }); + expect(patch?.init.body).toMatchObject({ value: "new_value" }); + }); + + it("updates file keys in the custom group, looking each up by group id", async () => { + const cwd = await pinnedCwd(); + await writeFile(path.join(cwd, ".env"), "API_KEY=new_value\n", "utf8"); + const staging = { + id: "vg_staging", + name: "staging", + class: "custom", + rule: { type: "equals", value: "staging" }, + }; + + const calls: Call[] = []; + const result = await makeCli( + variableClient({ + calls, + groups: [...BUILT_IN_GROUPS, staging], + routes: { + "GET /v1/environment-variables": () => ({ + data: { + data: [{ id: "ev_staging", key: "API_KEY" }], + pagination: { hasMore: false, nextCursor: null }, + }, + }), + "PATCH /v1/environment-variables/{envVarId}": () => ({ + data: { + data: { + id: "ev_staging", + key: "API_KEY", + updatedAt: "2024-06-01T00:00:00Z", + }, + }, + }), + }, + }), + ).run( + ["variable", "update", "--file", ".env", "--group", "staging", "--json"], + { cwd }, + ); + + expect(result.exitCode).toBe(0); + const lookup = calls.find( + (c) => c.method === "GET" && c.path === "/v1/environment-variables", + ); + expect(lookup?.init.params?.query).toMatchObject({ + key: "API_KEY", + groupId: "vg_staging", + }); + const patch = calls.find((c) => c.method === "PATCH"); + expect(patch?.init.params?.path).toMatchObject({ envVarId: "ev_staging" }); + }); + + it("fails with VARIABLE.NOT_FOUND when the variable does not exist in the group", async () => { + const result = await makeCli(variableClient()).run( + ["variable", "update", "MISSING=val", "--group", "production", "--json"], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.NOT_FOUND" }, + }); + }); +}); + +// --------------------------------------------------------------------------- +// variable delete +// --------------------------------------------------------------------------- + +describe("variable delete", () => { + it("DELETEs the matching variable by id", async () => { + const existingVar = { id: "ev_del", key: "OLD_KEY" }; + + const calls: Call[] = []; + const result = await makeCli( + variableClient({ + calls, + routes: { + "GET /v1/environment-variables": () => ({ + data: { + data: [existingVar], + pagination: { hasMore: false, nextCursor: null }, + }, + }), + "DELETE /v1/environment-variables/{envVarId}": () => ({ data: {} }), + }, + }), + ).run( + ["variable", "delete", "OLD_KEY", "--group", "production", "--json"], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(0); + + const del = calls.find( + (c) => + c.method === "DELETE" && + c.path === "/v1/environment-variables/{envVarId}", + ); + expect(del?.init.params?.path).toMatchObject({ envVarId: "ev_del" }); + }); + + it("fails with VARIABLE.NOT_FOUND when the variable does not exist", async () => { + const result = await makeCli(variableClient()).run( + ["variable", "delete", "GHOST", "--group", "production", "--json"], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.NOT_FOUND" }, + }); + }); +}); + +// --------------------------------------------------------------------------- +// variable list +// --------------------------------------------------------------------------- + +describe("variable list", () => { + it("renders a group table with variable counts", async () => { + const result = await makeCli( + variableClient({ + groups: ALL_GROUPS, + routes: { + "GET /v1/environment-variables": (call) => { + const groupId = (call.init.params?.query as { groupId?: string }) + ?.groupId; + if (groupId === "vg_prod") { + return { + data: { + data: [ + { + id: "ev_1", + key: "STRIPE_KEY", + updatedAt: "2024-01-01T00:00:00Z", + }, + ], + pagination: { hasMore: false, nextCursor: null }, + }, + }; + } + return { + data: { + data: [], + pagination: { hasMore: false, nextCursor: null }, + }, + }; + }, + }, + }), + ).run(["variable", "list", "--json"], { cwd: await pinnedCwd() }); + + expect(result.exitCode).toBe(0); + const envelope = resultFrame(result.json).envelope as { + ok: boolean; + result: { groups: Array<{ group: { name: string }; keys: string[] }> }; + }; + expect(envelope.ok).toBe(true); + const prodGroup = envelope.result.groups.find( + (g) => g.group.name === "production", + ); + expect(prodGroup?.keys).toEqual(["STRIPE_KEY"]); + }); +}); + +// --------------------------------------------------------------------------- +// variable group list +// --------------------------------------------------------------------------- + +describe("variable group list", () => { + it("renders a table with name, class, rule, and branch count", async () => { + const result = await makeCli(variableClient({ groups: ALL_GROUPS })).run( + ["variable", "group", "list"], + { cwd: await pinnedCwd(), isTty: { stdout: true } }, + ); + + expect(result.exitCode).toBe(0); + + const presented = result.presented as + | { presentation: { human: Array<{ kind: string }> } } + | undefined; + const human = presented?.presentation.human ?? []; + + expect(human).toContainEqual({ + kind: "table", + columns: ["name", "class", "rule", "branches"], + rows: expect.arrayContaining([ + ["production", "production", "production branch", "1"], + ["preview", "preview", "all other branches", "1"], + ["staging", "custom", "= staging", "1"], + ]), + }); + }); + + it("renders an empty-state summary when there are no groups", async () => { + const result = await makeCli(variableClient({ groups: [] })).run( + ["variable", "group", "list"], + { + cwd: await pinnedCwd(), + isTty: { stdout: true }, + }, + ); + + expect(result.exitCode).toBe(0); + const presented = result.presented as + | { presentation: { human: Array<{ kind: string; text?: string }> } } + | undefined; + const human = presented?.presentation.human ?? []; + expect(human).toContainEqual( + expect.objectContaining({ + kind: "summary", + text: "No variable groups found.", + }), + ); + }); +}); + +// --------------------------------------------------------------------------- +// variable group create +// --------------------------------------------------------------------------- + +describe("variable group create", () => { + it("POSTs an equals rule to /v1/variable-groups", async () => { + const calls: Call[] = []; + const result = await makeCli(variableClient({ calls })).run( + [ + "variable", + "group", + "create", + "staging", + "--equals", + "staging", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(0); + + const post = calls.find( + (c) => c.method === "POST" && c.path === "/v1/variable-groups", + ); + expect(post?.init.body).toMatchObject({ + projectId: "proj_1", + name: "staging", + rule: { type: "equals", value: "staging" }, + }); + }); + + it("POSTs a startsWith rule when --starts-with is given", async () => { + const calls: Call[] = []; + await makeCli(variableClient({ calls })).run( + [ + "variable", + "group", + "create", + "features", + "--starts-with", + "feat/", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + const post = calls.find( + (c) => c.method === "POST" && c.path === "/v1/variable-groups", + ); + expect(post?.init.body).toMatchObject({ + rule: { type: "startsWith", value: "feat/" }, + }); + }); + + it("fails when neither --equals nor --starts-with is given", async () => { + const result = await makeCli(variableClient()).run( + ["variable", "group", "create", "staging", "--json"], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.GROUP_RULE_MISSING" }, + }); + }); + + it("fails when both --equals and --starts-with are given", async () => { + const result = await makeCli(variableClient()).run( + [ + "variable", + "group", + "create", + "staging", + "--equals", + "staging", + "--starts-with", + "stag", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.GROUP_RULE_CONFLICT" }, + }); + }); +}); + +// --------------------------------------------------------------------------- +// variable group delete +// --------------------------------------------------------------------------- + +describe("variable group delete", () => { + it("DELETEs the group by id when --yes is passed", async () => { + const calls: Call[] = []; + const result = await makeCli( + variableClient({ + calls, + groups: ALL_GROUPS, + routes: { + "GET /v1/variable-groups": () => ({ + data: { data: ALL_GROUPS }, + }), + "DELETE /v1/variable-groups/{groupId}": () => ({ data: {} }), + }, + }), + ).run( + [ + "variable", + "group", + "delete", + "staging", + "--confirm", + "staging", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(0); + + const del = calls.find( + (c) => + c.method === "DELETE" && c.path === "/v1/variable-groups/{groupId}", + ); + expect(del?.init.params?.path).toMatchObject({ groupId: "vg_custom" }); + }); + + it("rejects deletion of the built-in production group", async () => { + const result = await makeCli( + variableClient({ groups: BUILT_IN_GROUPS }), + ).run( + [ + "variable", + "group", + "delete", + "production", + "--confirm", + "production", + "--json", + ], + { cwd: await pinnedCwd() }, + ); + + expect(result.exitCode).toBe(2); + expect(resultFrame(result.json).envelope).toMatchObject({ + ok: false, + error: { code: "VARIABLE.BUILTIN_GROUP_DELETE" }, + }); + }); +});