gencow 0.1.281 → 0.1.283

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.
@@ -0,0 +1,224 @@
1
+ // Pure parsing, validation and rendering helpers for `gencow credits` / `gencow usage`.
2
+ // The Platform `usage.byUser` payload is the only data source; unknown fields are ignored so
3
+ // additive server changes never break the CLI, and the account user id is never carried forward.
4
+
5
+ import { BOLD, CYAN, DIM, RESET } from "./output.mjs";
6
+
7
+ const MONTH_PATTERN = /^\d{4}-(0[1-9]|1[0-2])$/u;
8
+ const SAFE_TEXT_PATTERN = /^[A-Za-z0-9 _.:/@()\-]{1,200}$/u;
9
+ const SAFE_CODE_PATTERN = /^[A-Z][A-Z0-9_]{2,80}$/u;
10
+ const SAFE_CORRELATION_PATTERN = /^[A-Za-z0-9_-]{8,128}$/u;
11
+
12
+ const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
+ const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
14
+ const text = (value) => (typeof value === "string" && value.length > 0 ? value : null);
15
+
16
+ export function parseUsageMonth(value, now = new Date()) {
17
+ if (value === undefined) return { ok: true, month: undefined };
18
+ if (typeof value !== "string" || !MONTH_PATTERN.test(value)) {
19
+ return { ok: false, message: "Invalid --month. Use the YYYY-MM format, for example 2026-10." };
20
+ }
21
+ const current = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}`;
22
+ if (value > current) {
23
+ return { ok: false, message: `Invalid --month. ${value} is in the future (latest allowed: ${current}).` };
24
+ }
25
+ return { ok: true, month: value };
26
+ }
27
+
28
+ function readCredits(value) {
29
+ if (!isRecord(value)) return null;
30
+ const total = num(value.total);
31
+ const used = num(value.used);
32
+ const remaining = num(value.remaining);
33
+ return total === null || used === null || remaining === null ? null : { total, used, remaining };
34
+ }
35
+
36
+ function readServiceCredits(value) {
37
+ if (!isRecord(value)) return null;
38
+ const balance = num(value.balance);
39
+ if (balance === null) return null;
40
+ return {
41
+ balance,
42
+ periodUsed: num(value.periodUsed) ?? 0,
43
+ spendCapEnabled: value.spendCapEnabled === true,
44
+ spendCapAmount: num(value.spendCapAmount),
45
+ };
46
+ }
47
+
48
+ export function parseUsagePayload(value) {
49
+ if (!isRecord(value)) return null;
50
+ const plan = text(value.planDisplayName) ?? text(value.plan);
51
+ const platformCredits = readCredits(value.credits);
52
+ const serviceCredits = readServiceCredits(value.serviceCredits);
53
+ if (!plan || !platformCredits || !serviceCredits) return null;
54
+
55
+ const period = isRecord(value.period)
56
+ ? { start: text(value.period.start), end: text(value.period.end) }
57
+ : { start: null, end: null };
58
+ const spendCap = isRecord(value.spendCap)
59
+ ? { enabled: value.spendCap.enabled === true, amount: num(value.spendCap.amount) }
60
+ : { enabled: false, amount: null };
61
+ const serviceUsage = (Array.isArray(value.serviceUsageBreakdown) ? value.serviceUsageBreakdown : [])
62
+ .filter(isRecord)
63
+ .map((row) => ({
64
+ service: text(row.serviceType) ?? "unknown",
65
+ provider: text(row.provider),
66
+ unit: text(row.unitLabel),
67
+ quantity: num(row.unitQuantity) ?? 0,
68
+ credits: num(row.chargedCredits) ?? 0,
69
+ }));
70
+ const apps = (Array.isArray(value.apps) ? value.apps : [])
71
+ .filter((row) => isRecord(row) && text(row.appId))
72
+ .map((row) => ({
73
+ name: row.appId,
74
+ status: text(row.status) ?? "unknown",
75
+ platformCreditsUsed: num(row.creditsUsed) ?? 0,
76
+ serviceCreditsUsed: num(row.serviceCreditsUsed) ?? 0,
77
+ }));
78
+ const measurement = isRecord(value.measurement)
79
+ ? { status: text(value.measurement.status) ?? "unknown", lastUpdatedAt: text(value.measurement.lastUpdatedAt) }
80
+ : { status: "unknown", lastUpdatedAt: null };
81
+
82
+ return { plan, period, platformCredits, serviceCredits, spendCap, serviceUsage, apps, measurement };
83
+ }
84
+
85
+ export function toCreditsJson(summary) {
86
+ return {
87
+ plan: summary.plan,
88
+ period: summary.period,
89
+ platformCredits: summary.platformCredits,
90
+ serviceCredits: {
91
+ balance: summary.serviceCredits.balance,
92
+ periodUsed: summary.serviceCredits.periodUsed,
93
+ spendCapEnabled: summary.serviceCredits.spendCapEnabled,
94
+ spendCapAmount: summary.serviceCredits.spendCapAmount,
95
+ },
96
+ spendCap: summary.spendCap,
97
+ };
98
+ }
99
+
100
+ export function toUsageJson(summary, appFilter) {
101
+ return {
102
+ ...toCreditsJson(summary),
103
+ serviceUsage: summary.serviceUsage,
104
+ apps: filterApps(summary.apps, appFilter),
105
+ measurement: summary.measurement,
106
+ };
107
+ }
108
+
109
+ export function filterApps(apps, appFilter) {
110
+ return appFilter ? apps.filter((app) => app.name === appFilter) : apps;
111
+ }
112
+
113
+ export const formatNumber = (value) =>
114
+ value.toLocaleString("en-US", { maximumFractionDigits: 2 });
115
+
116
+ function formatDate(iso) {
117
+ return iso ? iso.slice(0, 10) : "—";
118
+ }
119
+
120
+ export function formatCreditsLines(summary) {
121
+ const { serviceCredits, platformCredits, spendCap, period } = summary;
122
+ const lines = [
123
+ "",
124
+ `${BOLD}${CYAN}Credits${RESET} ${DIM}plan: ${summary.plan}${RESET}`,
125
+ ` Service credits (AI / media) ${BOLD}${formatNumber(serviceCredits.balance)}${RESET} remaining`,
126
+ ` Platform credits ${BOLD}${formatNumber(platformCredits.remaining)}${RESET} remaining ${DIM}of ${formatNumber(platformCredits.total)}${RESET}`,
127
+ ` ${DIM}Period ${formatDate(period.start)} → ${formatDate(period.end)} · used this period: service ${formatNumber(serviceCredits.periodUsed)}, platform ${formatNumber(platformCredits.used)}${RESET}`,
128
+ ];
129
+ if (serviceCredits.spendCapEnabled) {
130
+ lines.push(` ${DIM}Service spend cap: ${serviceCredits.spendCapAmount === null ? "on" : formatNumber(serviceCredits.spendCapAmount)}${RESET}`);
131
+ }
132
+ if (spendCap.enabled) {
133
+ lines.push(` ${DIM}Platform spend cap: ${spendCap.amount === null ? "on" : formatNumber(spendCap.amount)}${RESET}`);
134
+ }
135
+ lines.push("");
136
+ return lines;
137
+ }
138
+
139
+ export function formatUsageLines(summary, appFilter) {
140
+ const apps = filterApps(summary.apps, appFilter);
141
+ const lines = formatCreditsLines(summary);
142
+ lines.push(`${BOLD}${CYAN}Usage by app${RESET}`);
143
+ if (apps.length === 0) {
144
+ lines.push(` ${DIM}No apps.${RESET}`);
145
+ } else {
146
+ lines.push(` ${"APP".padEnd(24)} ${"STATUS".padEnd(10)} ${"PLATFORM".padStart(10)} ${"SERVICE".padStart(10)}`);
147
+ for (const app of apps) {
148
+ lines.push(
149
+ ` ${app.name.padEnd(24)} ${app.status.padEnd(10)} ${formatNumber(app.platformCreditsUsed).padStart(10)} ${formatNumber(app.serviceCreditsUsed).padStart(10)}`,
150
+ );
151
+ }
152
+ }
153
+ if (!appFilter && summary.serviceUsage.length > 0) {
154
+ lines.push("", `${BOLD}${CYAN}Service usage${RESET}`);
155
+ for (const row of summary.serviceUsage) {
156
+ const via = row.provider ? ` (${row.provider})` : "";
157
+ const unit = row.unit ? ` ${row.unit}` : "";
158
+ lines.push(` ${(row.service + via).padEnd(28)} ${formatNumber(row.quantity)}${unit} → ${formatNumber(row.credits)} credits`);
159
+ }
160
+ }
161
+ if (summary.measurement.status !== "ready" && summary.measurement.status !== "unknown") {
162
+ lines.push("", ` ${DIM}Measurement status: ${summary.measurement.status} — recent usage may not be fully reflected yet.${RESET}`);
163
+ }
164
+ lines.push("");
165
+ return lines;
166
+ }
167
+
168
+ function safeText(value) {
169
+ return typeof value === "string" && SAFE_TEXT_PATTERN.test(value) ? value : null;
170
+ }
171
+
172
+ /**
173
+ * Render a failed Platform response using only the typed, public diagnostic fields.
174
+ * Unknown shapes fall back to a status-derived, non-support-escalating message.
175
+ */
176
+ export function formatUsageFailure(response, body, { command }) {
177
+ const status = response?.status;
178
+ const typed = isRecord(body) && SAFE_CODE_PATTERN.test(String(body.code ?? ""));
179
+ const lines = [];
180
+ if (typed) {
181
+ lines.push(safeText(body.error) ?? `gencow ${command} could not complete.`);
182
+ lines.push(`Code: ${body.code}`);
183
+ if (safeText(body.stage)) lines.push(`Stage: ${body.stage}`);
184
+ if (body.stateChanged === false) lines.push("State: nothing was changed.");
185
+ if (typeof body.retryable === "boolean") lines.push(`Retryable: ${body.retryable ? "yes" : "no"}`);
186
+ if (safeText(body.nextAction)) lines.push(`Next: ${body.nextAction}`);
187
+ } else if (status === 401) {
188
+ lines.push("You are not signed in, or your session has expired.");
189
+ lines.push("Code: CLI_AUTH_REQUIRED", "State: nothing was changed.", "Retryable: no", "Next: gencow login");
190
+ } else if (status === 503) {
191
+ lines.push("The Gencow Platform is temporarily unavailable.");
192
+ lines.push("Code: CLI_PLATFORM_UNAVAILABLE", "State: nothing was changed.", "Retryable: yes");
193
+ lines.push(`Next: wait a moment, then run gencow ${command} again.`);
194
+ } else {
195
+ lines.push(`gencow ${command} failed (HTTP ${Number.isInteger(status) ? status : "unknown"}).`);
196
+ lines.push("Code: CLI_PLATFORM_REQUEST_FAILED", "State: nothing was changed.");
197
+ lines.push(`Next: run gencow ${command} again; if it keeps failing, run gencow doctor and include the correlation ID below.`);
198
+ }
199
+ const correlation = response?.headers?.get?.("x-correlation-id") ?? response?.headers?.get?.("x-request-id");
200
+ if (typeof correlation === "string" && SAFE_CORRELATION_PATTERN.test(correlation)) {
201
+ lines.push(`Correlation: ${correlation}`);
202
+ }
203
+ return lines.join("\n");
204
+ }
205
+
206
+ export function formatUnreachable({ command }) {
207
+ return [
208
+ "Could not reach the Gencow Platform.",
209
+ "Code: CLI_PLATFORM_UNREACHABLE",
210
+ "State: nothing was changed.",
211
+ "Retryable: yes",
212
+ `Next: check your network connection, then run gencow ${command} again.`,
213
+ ].join("\n");
214
+ }
215
+
216
+ export function formatInvalidResponse({ command }) {
217
+ return [
218
+ `The Platform returned data gencow ${command} does not understand.`,
219
+ "Code: CLI_USAGE_RESPONSE_INVALID",
220
+ "State: nothing was changed (read-only command).",
221
+ "Retryable: yes",
222
+ "Next: update the CLI with npx gencow@latest, then retry.",
223
+ ].join("\n");
224
+ }
@@ -12,6 +12,7 @@ import { readJsonValueResponse } from "./http-response-json.mjs";
12
12
  import { renderDeployFailureDiagnosticLines } from "./deploy-failure-diagnostic.mjs";
13
13
  import { formatAppLogDiagnosis } from "./deploy-logs-diagnostic.mjs";
14
14
  import { formatDeploymentOperationPhase } from "./deployment-operation-poll.mjs";
15
+ import { handleDeployReleaseSubcommand } from "./release-history-command.mjs";
15
16
 
16
17
  export function renderDeployHelp() {
17
18
  log(`\n${BOLD}${CYAN}gencow deploy${RESET} — Deploy backend or fullstack app to cloud\n`);
@@ -23,6 +24,8 @@ export function renderDeployHelp() {
23
24
  log(` ${DIM}--prod${RESET} Deploy to production (Startup/Enterprise)`);
24
25
  log(` ${DIM}--region <slug>${RESET} First production app placement region`);
25
26
  log(` ${DIM}--rollback${RESET} Rollback to previous deployment`);
27
+ log(` ${DIM}history${RESET} List retained releases (deploy history [--prod] [--json])`);
28
+ log(` ${DIM}rollback <version>${RESET} Restore a static release (deploy rollback v2 [--prod] [--yes])`);
26
29
  log(` ${DIM}--force, -f${RESET} Skip optional dependency scan`);
27
30
  log(` ${DIM}--resume <request-id>${RESET} Resume an exact interrupted deploy`);
28
31
  log(` ${DIM}--app, -a${RESET} Target specific app\n`);
@@ -168,6 +171,7 @@ export async function handleDeployReadonlySubcommand(params) {
168
171
  infoImpl = info,
169
172
  logImpl = log,
170
173
  } = params;
174
+ if (await handleDeployReleaseSubcommand(params)) return true;
171
175
  const knownSubcmds = new Set(["logs", "status"]);
172
176
  if (deployArgs.length === 0 || !knownSubcmds.has(deployArgs[0])) {
173
177
  return false;
@@ -6,6 +6,7 @@ import { prodRetryCommandLine, reconcileProductionAppTarget } from "./deploy-app
6
6
  import { readJsonObjectResponse } from "./http-response-json.mjs";
7
7
  import { BOLD, DIM, GREEN, RED, RESET, error, info, log, success } from "./output.mjs";
8
8
  import { prodCreateFailureMessage } from "./prod-create-failure.mjs";
9
+ import { credentialEnvNameOf } from "./prod-create-auth-diagnostic.mjs";
9
10
 
10
11
  export async function ensureProductionDeployTarget({
11
12
  appId,
@@ -110,7 +111,12 @@ export async function ensureProductionDeployTarget({
110
111
  logImpl(` ${GREEN}gencow upgrade${RESET} ${DIM}← Upgrade to Startup${RESET}`);
111
112
  logImpl("");
112
113
  } else {
113
- errorImpl(prodCreateFailureMessage(errData, createProdRes, { requestedRegion: region }));
114
+ errorImpl(
115
+ prodCreateFailureMessage(errData, createProdRes, {
116
+ requestedRegion: region,
117
+ credentialEnvName: credentialEnvNameOf(creds),
118
+ }),
119
+ );
114
120
  }
115
121
  exitImpl(1);
116
122
  return null;
@@ -0,0 +1,87 @@
1
+ import { authCauseNextAction, safeAuthCauseCode } from "./release-auth-cause.mjs";
2
+
3
+ /**
4
+ * Renders the typed auth rejection from a create-prod response: 503 AUTH_LOOKUP_UNAVAILABLE
5
+ * (temporary lookup failure) or 401 with a credential code or an account lifecycle code.
6
+ * Every field is allow-listed. The message text comes from this file, never from the server body.
7
+ */
8
+ const CREDENTIAL_REJECTED_CODE = "APP_CREATE_AUTH_REQUIRED";
9
+ const LOOKUP_UNAVAILABLE_CODE = "AUTH_LOOKUP_UNAVAILABLE";
10
+ const ACCOUNT_MESSAGES = new Map([
11
+ ["ACCOUNT_DELETED", "This account has been deleted."],
12
+ ["ACCOUNT_DELETION_PENDING", "This account is pending deletion."],
13
+ ["ACCOUNT_SUSPENDED", "This account is suspended."],
14
+ ]);
15
+ const CORRELATION_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/u;
16
+ const ACCOUNT_NEXT_ACTION =
17
+ "running `gencow login` or `gencow whoami` does not change the account state. Check the account status in the Gencow dashboard, then run the command again.";
18
+
19
+ export function readCreateProdAuthDiagnostic(body, response) {
20
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
21
+ if (body.stage !== "auth") return null;
22
+ const correlationId =
23
+ typeof body.correlationId === "string" && CORRELATION_ID_PATTERN.test(body.correlationId)
24
+ ? body.correlationId
25
+ : null;
26
+
27
+ if (response?.status === 503 && body.code === LOOKUP_UNAVAILABLE_CODE) {
28
+ return { kind: "unavailable", code: LOOKUP_UNAVAILABLE_CODE, correlationId };
29
+ }
30
+ if (response?.status !== 401) return null;
31
+ if (body.code === CREDENTIAL_REJECTED_CODE) {
32
+ return {
33
+ kind: "credential",
34
+ code: CREDENTIAL_REJECTED_CODE,
35
+ causeCode: safeAuthCauseCode(body.causeCode),
36
+ correlationId,
37
+ };
38
+ }
39
+ if (ACCOUNT_MESSAGES.has(body.code)) {
40
+ return { kind: "account", code: body.code, correlationId };
41
+ }
42
+ return null;
43
+ }
44
+
45
+ // The env credential that overrides `gencow login`, or null. Same rule as the deploy target helpers.
46
+ export function credentialEnvNameOf(creds) {
47
+ return creds?.credentialSource === "environment" &&
48
+ (creds.credentialEnvName === "GENCOW_TOKEN" || creds.credentialEnvName === "GENCOW_DEPLOY_TOKEN")
49
+ ? creds.credentialEnvName
50
+ : null;
51
+ }
52
+
53
+ export function formatCreateProdAuthMessage(diagnostic, credentialEnvName = null) {
54
+ const correlation = diagnostic.correlationId ?? "none returned";
55
+ if (diagnostic.kind === "unavailable") {
56
+ return [
57
+ "Prod app creation failed: Authentication lookup temporarily unavailable",
58
+ `Code: ${diagnostic.code}`,
59
+ "Stage: auth",
60
+ "Changed: nothing (no prod app was created)",
61
+ "Retryable: yes",
62
+ "Next: wait a short while, then run the same command again. If it keeps failing, send the Correlation ID.",
63
+ `Correlation ID: ${correlation}`,
64
+ ].join("\n");
65
+ }
66
+ if (diagnostic.kind === "account") {
67
+ return [
68
+ `Prod app creation failed: ${ACCOUNT_MESSAGES.get(diagnostic.code)}`,
69
+ `Code: ${diagnostic.code}`,
70
+ "Stage: auth",
71
+ "Changed: nothing (no prod app was created)",
72
+ "Retryable: no",
73
+ `Next: ${ACCOUNT_NEXT_ACTION}`,
74
+ `Correlation ID: ${correlation}`,
75
+ ].join("\n");
76
+ }
77
+ const lines = [
78
+ "Prod app creation failed: CLI authentication is required",
79
+ `Code: ${diagnostic.code}`,
80
+ "Stage: auth",
81
+ ];
82
+ if (diagnostic.causeCode) lines.push(`Cause: ${diagnostic.causeCode}`);
83
+ lines.push("Changed: nothing (no prod app was created)", "Retryable: no");
84
+ lines.push(`Next: ${authCauseNextAction(credentialEnvName)}`);
85
+ lines.push(`Correlation ID: ${correlation}`);
86
+ return lines.join("\n");
87
+ }
@@ -3,6 +3,7 @@ import {
3
3
  formatRegionUnavailableMessage,
4
4
  readRegionUnavailableDiagnostic,
5
5
  } from "./prod-create-region-diagnostic.mjs";
6
+ import { formatCreateProdAuthMessage, readCreateProdAuthDiagnostic } from "./prod-create-auth-diagnostic.mjs";
6
7
 
7
8
  /** One rendering of a failed `create-prod` response for every CLI deploy path. */
8
9
  export function prodCreateFailureMessage(errData, response, options = {}) {
@@ -10,6 +11,8 @@ export function prodCreateFailureMessage(errData, response, options = {}) {
10
11
  response.status === 503
11
12
  ? "Prod app creation is temporarily unavailable."
12
13
  : errData?.error || response.statusText || `HTTP ${response.status}`;
14
+ const authDiagnostic = readCreateProdAuthDiagnostic(errData, response);
15
+ if (authDiagnostic) return formatCreateProdAuthMessage(authDiagnostic, options.credentialEnvName ?? null);
13
16
  const regionDiagnostic = readRegionUnavailableDiagnostic(errData, response);
14
17
  if (regionDiagnostic) {
15
18
  return formatRegionUnavailableMessage(regionDiagnostic, fallback, options.requestedRegion ?? null);
@@ -0,0 +1,239 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import { resolveCloudAppTargetWithServerEnvironment } from "./cloud-target-environment.mjs";
4
+ import {
5
+ CONFIRMATION_MODE,
6
+ askConfirmation,
7
+ buildConfirmationRequiredDiagnostic,
8
+ renderConfirmationRequired,
9
+ resolveConfirmationMode,
10
+ } from "./confirm-gate.mjs";
11
+ import { cloudTargetRejectionMessage, prodRetryCommandLine } from "./deploy-app-target.mjs";
12
+ import { readJsonValueResponse } from "./http-response-json.mjs";
13
+ import { GREEN, RESET, YELLOW, error, info, log } from "./output.mjs";
14
+ import {
15
+ correlationOf,
16
+ formatHistoryLines,
17
+ isTypedFailure,
18
+ parseReleaseList,
19
+ releaseFailureCode,
20
+ renderReleaseFailure,
21
+ resolveReleaseVersion,
22
+ restorableVersions,
23
+ toHistoryJson,
24
+ } from "./release-history-format.mjs";
25
+
26
+ const SUBCOMMANDS = new Set(["history", "rollback"]);
27
+ const TERMINAL_FAILURE_STATES = new Set(["failed", "compensation_required"]);
28
+ const POLL_INTERVAL_MS = 2000;
29
+ const MAX_POLLS = 90;
30
+ const MAX_SUBMIT_ATTEMPTS = 3;
31
+
32
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
33
+
34
+ function splitArgs(args) {
35
+ const flags = { json: false, yes: false };
36
+ const targetArgs = [];
37
+ const positional = [];
38
+ for (let i = 0; i < args.length; i++) {
39
+ const arg = args[i];
40
+ if (arg === "--json") flags.json = true;
41
+ else if (arg === "--yes" || arg === "-y") flags.yes = true;
42
+ else if (arg === "--prod") targetArgs.push(arg);
43
+ else if (arg === "--app" || arg === "-a") targetArgs.push(arg, args[++i] ?? "");
44
+ else if (arg.startsWith("-")) targetArgs.push(arg);
45
+ else positional.push(arg);
46
+ }
47
+ return { flags, targetArgs, positional };
48
+ }
49
+
50
+ async function readBody(response) {
51
+ const decoded = await readJsonValueResponse(response).catch(() => ({ parsed: false }));
52
+ return decoded.parsed ? decoded.value : null;
53
+ }
54
+
55
+ export async function handleDeployReleaseSubcommand(params) {
56
+ const { deployArgs } = params;
57
+ if (!deployArgs?.length || !SUBCOMMANDS.has(deployArgs[0])) return false;
58
+ const {
59
+ creds,
60
+ cwd = process.cwd(),
61
+ errorImpl = error,
62
+ infoImpl = info,
63
+ logImpl = log,
64
+ exitImpl = process.exit,
65
+ platformFetchImpl,
66
+ rpcQueryImpl,
67
+ processEnv = process.env,
68
+ createInterfaceImpl,
69
+ sleepImpl = defaultSleep,
70
+ maxPolls = MAX_POLLS,
71
+ } = params;
72
+ const subcmd = deployArgs[0];
73
+ const { flags, targetArgs, positional } = splitArgs(deployArgs.slice(1));
74
+ const fail = (code, options) => {
75
+ errorImpl(renderReleaseFailure(code, options));
76
+ exitImpl(1);
77
+ return true;
78
+ };
79
+
80
+ const resolveTarget =
81
+ params.resolveTargetImpl ??
82
+ ((args) =>
83
+ resolveCloudAppTargetWithServerEnvironment(args, {
84
+ cwd,
85
+ creds,
86
+ rpcQueryImpl,
87
+ stage: "deploy target resolution",
88
+ command: `deploy ${subcmd}`,
89
+ missingAppMessage: "App not found. Run from the project root with gencow.json.",
90
+ missingProdMessage: "No prod app yet. Run gencow deploy --prod first.",
91
+ }));
92
+ const target = await resolveTarget(targetArgs);
93
+ if (target.error) {
94
+ errorImpl(
95
+ cloudTargetRejectionMessage(target, {
96
+ fallbackMessage: target.error,
97
+ stage: "deploy target resolution",
98
+ changed: "nothing. Release data was only read; no app or serving state was changed.",
99
+ next: `${prodRetryCommandLine({ command: "deploy", args: deployArgs })} (omit --app to target this project's prod app)`,
100
+ }),
101
+ );
102
+ exitImpl(1);
103
+ return true;
104
+ }
105
+ const { appId, envTarget } = target;
106
+ const base = `/platform/apps/${encodeURIComponent(appId)}`;
107
+
108
+ // ── load the retained releases (shared by history and rollback) ──────────────
109
+ let listResponse;
110
+ try {
111
+ listResponse = await platformFetchImpl(creds, `${base}/releases?environment=${envTarget}`, { method: "GET" });
112
+ } catch {
113
+ return fail("CLI_PLATFORM_UNREACHABLE");
114
+ }
115
+ const listBody = await readBody(listResponse);
116
+ if (!listResponse.ok) {
117
+ return fail(releaseFailureCode(listResponse, listBody), { correlation: correlationOf(listResponse) });
118
+ }
119
+ const list = parseReleaseList(listBody);
120
+ if (!list) return fail("CLI_RELEASE_RESPONSE_INVALID", { correlation: correlationOf(listResponse) });
121
+
122
+ if (subcmd === "history") {
123
+ if (flags.json) {
124
+ logImpl(JSON.stringify(toHistoryJson(list), null, 2));
125
+ } else if (list.releases.length === 0) {
126
+ infoImpl("No retained releases yet. Deploy once with: gencow deploy" + (envTarget === "prod" ? " --prod" : ""));
127
+ } else {
128
+ for (const line of formatHistoryLines(list, appId)) logImpl(line);
129
+ }
130
+ return true;
131
+ }
132
+
133
+ // ── rollback <version> ───────────────────────────────────────────────────────
134
+ const available = restorableVersions(list.releases);
135
+ const availableHint = `Restorable versions: ${available.join(", ") || "none"}`;
136
+ if (positional.length !== 1) return fail("CLI_ROLLBACK_USAGE_INVALID", { extra: availableHint });
137
+ const resolved = resolveReleaseVersion(positional[0], list.releases);
138
+ if (resolved.kind === "invalid") return fail("CLI_ROLLBACK_USAGE_INVALID", { extra: availableHint });
139
+ if (resolved.kind === "not_found") {
140
+ return fail("APP_RELEASE_NOT_FOUND", { detail: `Version: v${resolved.version}`, extra: availableHint });
141
+ }
142
+ const { release } = resolved;
143
+ if (release.current) {
144
+ infoImpl(`v${release.version} is already active on ${appId} (${envTarget}). Nothing to do.`);
145
+ return true;
146
+ }
147
+ if (!release.restoreAvailable) {
148
+ return fail("APP_RELEASE_NOT_RESTORABLE", { detail: `Version: v${release.version}`, extra: availableHint });
149
+ }
150
+
151
+ if (envTarget === "prod") {
152
+ const mode = resolveConfirmationMode({ args: flags.yes ? ["--yes"] : [], processEnv, createInterfaceImpl });
153
+ if (mode === CONFIRMATION_MODE.PROMPT) {
154
+ const createInterface = createInterfaceImpl ?? (await import("node:readline")).createInterface;
155
+ logImpl("");
156
+ logImpl(` Restore v${release.version} on production app ${appId}? Static files switch to that version; data is not changed.`);
157
+ const answer = await askConfirmation({
158
+ createInterface,
159
+ prompt: ` ${YELLOW}⚠${RESET} Proceed? (y/N) `,
160
+ output: process.stdout,
161
+ });
162
+ if (answer !== null && answer.trim().toLowerCase() !== "y") {
163
+ infoImpl("Rollback cancelled. Nothing was changed.");
164
+ return true;
165
+ }
166
+ if (answer === null) return confirmationRequired({ inputEnded: true });
167
+ } else if (mode === CONFIRMATION_MODE.NON_INTERACTIVE) {
168
+ return confirmationRequired({ inputEnded: false });
169
+ }
170
+ }
171
+
172
+ function confirmationRequired({ inputEnded }) {
173
+ renderConfirmationRequired(
174
+ buildConfirmationRequiredDiagnostic({
175
+ correlationId: `rollback_${randomUUID()}`,
176
+ inputEnded,
177
+ retryCommand: `gencow deploy rollback v${release.version} --prod --yes`,
178
+ subject: `Restoring v${release.version} on production needs confirmation.`,
179
+ }),
180
+ { errorImpl, logImpl },
181
+ );
182
+ exitImpl(1);
183
+ return true;
184
+ }
185
+
186
+ // One key per invocation: a retry of this same command run reuses it, so a lost response can never create a second restore.
187
+ const idempotencyKey = `gencow-rollback-${randomUUID()}`;
188
+ let submit = null;
189
+ for (let attempt = 1; attempt <= MAX_SUBMIT_ATTEMPTS; attempt++) {
190
+ try {
191
+ submit = await platformFetchImpl(creds, `${base}/releases/${encodeURIComponent(release.id)}/restore`, {
192
+ method: "POST",
193
+ headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
194
+ body: JSON.stringify({ environment: envTarget }),
195
+ });
196
+ } catch {
197
+ submit = null;
198
+ }
199
+ const transient = submit === null || (submit.status >= 500 && !isTypedFailure(await peekBody(submit)));
200
+ if (!transient) break;
201
+ if (attempt < MAX_SUBMIT_ATTEMPTS) await sleepImpl(POLL_INTERVAL_MS);
202
+ }
203
+ if (submit === null) return fail("CLI_PLATFORM_UNREACHABLE");
204
+ const submitBody = await readBody(submit);
205
+ if (!submit.ok) return fail(releaseFailureCode(submit, submitBody), { correlation: correlationOf(submit) });
206
+ const operationId = submitBody?.operation?.id;
207
+ if (typeof operationId !== "string" || operationId.length === 0) {
208
+ return fail("CLI_RELEASE_RESPONSE_INVALID", { correlation: correlationOf(submit) });
209
+ }
210
+
211
+ infoImpl(`Restoring v${release.version} on ${appId} (${envTarget})...`);
212
+ for (let poll = 0; poll < maxPolls; poll++) {
213
+ let pollResponse;
214
+ try {
215
+ pollResponse = await platformFetchImpl(creds, `${base}/release-restores/${encodeURIComponent(operationId)}`, { method: "GET" });
216
+ } catch {
217
+ pollResponse = null;
218
+ }
219
+ const pollBody = pollResponse?.ok ? await readBody(pollResponse) : null;
220
+ const operation = pollBody?.operation;
221
+ if (operation?.state === "succeeded") {
222
+ logImpl(`${GREEN} ✓${RESET} Restored v${release.version}. ${appId} (${envTarget}) now serves that version.`);
223
+ return true;
224
+ }
225
+ if (operation && TERMINAL_FAILURE_STATES.has(operation.state)) {
226
+ return fail(isTypedFailure({ code: operation.failureCode }) ? releaseFailureCode({ status: 409 }, { code: operation.failureCode }) : "APP_RELEASE_RESTORE_FAILED", {
227
+ correlation: correlationOf(pollResponse),
228
+ });
229
+ }
230
+ await sleepImpl(POLL_INTERVAL_MS);
231
+ }
232
+ return fail("APP_RELEASE_RESTORE_PENDING", { detail: `Operation: ${operationId}` });
233
+ }
234
+
235
+ async function peekBody(response) {
236
+ // The body is read once by the caller afterwards; clone when available so both reads work.
237
+ const source = typeof response.clone === "function" ? response.clone() : response;
238
+ return readBody(source);
239
+ }