gencow 0.1.281 → 0.1.282

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/gencow.mjs CHANGED
@@ -39,7 +39,7 @@ import { resolve, dirname } from "path";
39
39
  import { fileURLToPath } from "url";
40
40
  import { createAddCommand } from "../lib/add-command.mjs";
41
41
  import { createAuthCommands } from "../lib/auth-command.mjs";
42
- import { createAppCommand } from "../lib/app-command.mjs";
42
+ import { createAppCommand } from "../lib/app-command-composed.mjs";
43
43
  import { createBackupCommand } from "../lib/backup-command.mjs";
44
44
  import { createApiCodegenRuntime, resolveCoreImport } from "../lib/cli-dev-runtime.mjs";
45
45
  import {
@@ -67,6 +67,7 @@ import { createDevCloudCommand } from "../lib/dev-cloud-command.mjs";
67
67
  import { createDevLocalCommands } from "../lib/dev-local-command.mjs";
68
68
  import { handleDeployReadonlySubcommand, renderDeployHelp, verifyAppReady } from "../lib/deploy-command.mjs";
69
69
  import { createDeployCommand } from "../lib/deploy-runtime.mjs";
70
+ import { createCreditsCommands } from "../lib/credits-command.mjs";
70
71
  import { createDomainCommand } from "../lib/domain-command.mjs";
71
72
  import { createEnvCommand } from "../lib/env-command.mjs";
72
73
  import { createFilesCommand } from "../lib/files-command.mjs";
@@ -128,10 +129,7 @@ const runAddCommand = createAddCommand({
128
129
  RESET,
129
130
  YELLOW,
130
131
  });
131
- const runAppCommand = createAppCommand({
132
- loadConfig,
133
- errorImpl: (message) => console.error(`${RED} ✗${RESET} ${message}`),
134
- });
132
+ const runAppCommand = createAppCommand({ loadConfig, errorImpl: (message) => console.error(`${RED} ✗${RESET} ${message}`) });
135
133
  const runBackupCommand = createBackupCommand();
136
134
  const { login: runLoginCommand, logout: runLogoutCommand, whoami: runWhoamiCommand } = createAuthCommands();
137
135
  const runCodegenCommand = createCodegenCommand({
@@ -415,6 +413,8 @@ ${BOLD}Commands (login required):${RESET}
415
413
  ${GREEN}login${RESET} Login to Gencow Platform ${DIM}(browser → token)${RESET}
416
414
  ${GREEN}logout${RESET} Clear credentials
417
415
  ${GREEN}whoami${RESET} Show current user info
416
+ ${GREEN}credits${RESET} Show credit balance and plan ${DIM}(--json)${RESET}
417
+ ${GREEN}usage${RESET} Show usage by app/service ${DIM}(--month YYYY-MM, --app NAME, --json)${RESET}
418
418
  ${GREEN}dev${RESET} Watch + auto-deploy to cloud + live logs
419
419
  ${DIM}--local Run local Bun + Hono + PGlite development${RESET}
420
420
  ${DIM}--verbose Show all HTTP logs (including admin/ws)${RESET}
@@ -467,6 +467,7 @@ ${BOLD}App management:${RESET}
467
467
  ${GREEN}app create${RESET} Create a new app
468
468
  ${GREEN}app delete${RESET} Delete an app ${DIM}(confirmation required)${RESET}
469
469
  ${GREEN}app status${RESET} Show app status
470
+ ${GREEN}app stop|resume|wake${RESET} Control the app runtime ${DIM}(stop asks to confirm on prod)${RESET}
470
471
 
471
472
  ${BOLD}Ops (Observability):${RESET}
472
473
  ${GREEN}logs${RESET} Show local dev server logs ${DIM}(--lines N, --follow)${RESET}
@@ -517,6 +518,7 @@ ${BOLD}Examples:${RESET}
517
518
  login: runLoginCommand,
518
519
  logout: runLogoutCommand,
519
520
  whoami: runWhoamiCommand,
521
+ ...createCreditsCommands(),
520
522
 
521
523
  // ── static — 정적 파일 배포 (dev 기본, --prod 로 프로덕션) ──
522
524
  static: runStaticCommand,
@@ -554,8 +556,6 @@ ${BOLD}Examples:${RESET}
554
556
  // ── app (subcommands: create, list, delete) ────────
555
557
  app: runAppCommand,
556
558
 
557
- // ── remote:deploy — REMOVED (legacy, use `gencow deploy` instead) ──
558
-
559
559
  // ── jobs (Cron/Scheduled Jobs Observability) ──────
560
560
  jobs: runJobsCommand,
561
561
 
@@ -578,8 +578,6 @@ ${BOLD}Examples:${RESET}
578
578
  add: runAddCommand,
579
579
  };
580
580
 
581
- // ─── updateReadme: gencow/ 폴더 스캔 → README에 컴포넌트 문서 자동 추가 ────
582
-
583
581
  const [, , rawCmd = "help", ...rawArgs] = process.argv;
584
582
  const globalProjectSelection = parseProjectSelectionArgs(rawArgs);
585
583
  setCliInvocationSelection(globalProjectSelection);
@@ -0,0 +1,30 @@
1
+ // `gencow app` = the base app command (list/create/delete/status) plus the runtime lifecycle
2
+ // subcommands (stop/resume/wake). Kept separate so the base command module is not grown further.
3
+
4
+ import { createAppCommand as createBaseAppCommandDefault } from "./app-command.mjs";
5
+ import {
6
+ APP_LIFECYCLE_SUBCOMMANDS,
7
+ createAppLifecycleCommand,
8
+ renderAppLifecycleHelpLines,
9
+ } from "./app-lifecycle-command.mjs";
10
+ import { log } from "./output.mjs";
11
+
12
+ export function createAppCommand({
13
+ createBaseAppCommand = createBaseAppCommandDefault,
14
+ createLifecycleCommand = createAppLifecycleCommand,
15
+ logImpl = log,
16
+ ...baseOptions
17
+ } = {}) {
18
+ const base = createBaseAppCommand({ ...baseOptions, logImpl });
19
+ const lifecycle = createLifecycleCommand({ errorImpl: baseOptions.errorImpl, infoImpl: baseOptions.infoImpl, logImpl });
20
+ return async function app(subcmd, ...rest) {
21
+ if (APP_LIFECYCLE_SUBCOMMANDS.has(subcmd)) return lifecycle(subcmd, ...rest);
22
+ const result = await base(subcmd, ...rest);
23
+ if (subcmd === "--help" || subcmd === "-h") {
24
+ logImpl(" Runtime control:");
25
+ for (const line of renderAppLifecycleHelpLines()) logImpl(line);
26
+ logImpl("");
27
+ }
28
+ return result;
29
+ };
30
+ }
@@ -0,0 +1,210 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import { lookupAppEnvironment } 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 { readJsonValueResponse } from "./http-response-json.mjs";
12
+ import {
13
+ classifyLifecycleFailure,
14
+ correlationOf,
15
+ renderLifecycleFailure,
16
+ stopDiagnosticLines,
17
+ stopFailureCode,
18
+ } from "./app-lifecycle-format.mjs";
19
+ import { BOLD, CYAN, DIM, GREEN, RESET, YELLOW, error, info, log } from "./output.mjs";
20
+ import { loadCreds, requireCreds, rpcMutation, rpcQuery } from "./platform-client.mjs";
21
+
22
+ export const APP_LIFECYCLE_SUBCOMMANDS = new Set(["stop", "resume", "wake"]);
23
+
24
+ const POLL_INTERVAL_MS = 2000;
25
+ const DEFAULT_WAIT_SECONDS = 120;
26
+ const MAX_WAIT_SECONDS = 600;
27
+ const MUTATION = { stop: "apps.stop", resume: "apps.resume", wake: "apps.wake" };
28
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29
+
30
+ export function renderAppLifecycleHelpLines() {
31
+ return [
32
+ ` ${CYAN}stop${RESET} Stop the app runtime (data is kept; production asks to confirm)`,
33
+ ` ${CYAN}resume${RESET} Start a stopped app`,
34
+ ` ${CYAN}wake${RESET} Wake an idle app`,
35
+ ];
36
+ }
37
+
38
+ function parseArgs(rest) {
39
+ const parsed = { name: null, yes: false, cancel: undefined, waitSeconds: DEFAULT_WAIT_SECONDS, invalid: false };
40
+ for (let i = 0; i < rest.length; i++) {
41
+ const arg = rest[i];
42
+ if (arg === "--yes" || arg === "-y") parsed.yes = true;
43
+ else if (arg === "--prod") continue;
44
+ else if (arg === "--cancel") {
45
+ const value = rest[i + 1];
46
+ if (typeof value === "string" && value.length > 0 && !value.startsWith("-")) {
47
+ parsed.cancel = value;
48
+ i++;
49
+ } else parsed.invalid = true;
50
+ } else if (arg === "--wait") {
51
+ const seconds = Number(rest[++i]);
52
+ if (Number.isInteger(seconds) && seconds >= 1 && seconds <= MAX_WAIT_SECONDS) parsed.waitSeconds = seconds;
53
+ else parsed.invalid = true;
54
+ } else if (arg.startsWith("-")) parsed.invalid = true;
55
+ else if (parsed.name === null) parsed.name = arg;
56
+ else parsed.invalid = true;
57
+ }
58
+ return parsed;
59
+ }
60
+
61
+ export function createAppLifecycleCommand({
62
+ errorImpl = error,
63
+ infoImpl = info,
64
+ logImpl = log,
65
+ requireCredsImpl = requireCreds,
66
+ loadCredsImpl = loadCreds,
67
+ rpcMutationImpl = rpcMutation,
68
+ rpcQueryImpl = rpcQuery,
69
+ processEnv = process.env,
70
+ createInterfaceImpl,
71
+ sleepImpl = defaultSleep,
72
+ } = {}) {
73
+ const readBody = async (response) => {
74
+ const decoded = await readJsonValueResponse(response).catch(() => ({ parsed: false }));
75
+ return decoded.parsed ? decoded.value : null;
76
+ };
77
+
78
+ return async function lifecycle(subcmd, ...rest) {
79
+ if (!APP_LIFECYCLE_SUBCOMMANDS.has(subcmd)) return undefined;
80
+ if (rest.includes("--help") || rest.includes("-h")) {
81
+ logImpl(`\n${BOLD}${CYAN}gencow app ${subcmd}${RESET}\n`);
82
+ logImpl(` Usage: gencow app ${subcmd} [name]${subcmd === "stop" ? " [--yes] [--wait <seconds>] | --cancel <operation-id>" : ""}`);
83
+ logImpl(` ${DIM}Uses the linked app when no name is given. Needs your login session or an app-bound deploy token.${RESET}\n`);
84
+ return 0;
85
+ }
86
+
87
+ const args = parseArgs(rest);
88
+ const creds = requireCredsImpl({ throwOnMissing: true });
89
+ const name = args.name ?? loadCredsImpl()?.currentApp ?? null;
90
+ const fail = (code, options = {}) => {
91
+ errorImpl(renderLifecycleFailure(code, { name: name ?? undefined, ...options }));
92
+ return 1;
93
+ };
94
+ if (args.invalid || !name || (args.cancel !== undefined && subcmd !== "stop")) {
95
+ errorImpl(
96
+ `${renderLifecycleFailure("CLI_LIFECYCLE_USAGE_INVALID")}\nUsage: gencow app ${subcmd} <name>${subcmd === "stop" ? " [--yes] [--wait <seconds>] | --cancel <operation-id>" : ""}`,
97
+ );
98
+ return 1;
99
+ }
100
+
101
+ const mutate = async (mutationName, mutationArgs) => {
102
+ try {
103
+ const response = await rpcMutationImpl(creds, mutationName, mutationArgs);
104
+ return { response, body: await readBody(response) };
105
+ } catch {
106
+ return null;
107
+ }
108
+ };
109
+
110
+ if (subcmd === "stop" && args.cancel !== undefined) {
111
+ const result = await mutate("apps.stopCancel", { name, operationId: args.cancel });
112
+ if (!result) return fail("CLI_PLATFORM_UNREACHABLE");
113
+ if (!result.response.ok) {
114
+ return fail(classifyLifecycleFailure(result.response, result.body), { correlation: correlationOf(result.response, result.body) });
115
+ }
116
+ logImpl(`${GREEN} ✓${RESET} Stop operation cancelled. ${name} keeps its current runtime state.`);
117
+ return 0;
118
+ }
119
+
120
+ if (subcmd === "stop") {
121
+ const found = await lookupAppEnvironment({ creds, appId: name, rpcQueryImpl });
122
+ if (found.kind === "missing") return fail("APP_NOT_FOUND");
123
+ if (found.kind === "error") {
124
+ return fail(found.code === "APP_RELEASE_AUTH_REQUIRED" ? "CLI_AUTH_REQUIRED" : found.retryable ? "CLI_PLATFORM_UNAVAILABLE" : "APP_LIFECYCLE_FAILED", { correlation: found.correlationId });
125
+ }
126
+ if (found.environment === "production") {
127
+ const mode = resolveConfirmationMode({ args: args.yes ? ["--yes"] : [], processEnv, createInterfaceImpl });
128
+ if (mode === CONFIRMATION_MODE.PROMPT) {
129
+ const createInterface = createInterfaceImpl ?? (await import("node:readline")).createInterface;
130
+ logImpl("");
131
+ logImpl(` Stop production app ${name}? It stops answering requests until you run: gencow app resume ${name}. Data is kept.`);
132
+ const answer = await askConfirmation({ createInterface, prompt: ` ${YELLOW}⚠${RESET} Proceed? (y/N) `, output: process.stdout });
133
+ if (answer !== null && answer.trim().toLowerCase() !== "y") {
134
+ infoImpl("Stop cancelled. Nothing was changed.");
135
+ return 0;
136
+ }
137
+ if (answer === null) return confirmationRequired(true);
138
+ } else if (mode === CONFIRMATION_MODE.NON_INTERACTIVE) {
139
+ return confirmationRequired(false);
140
+ }
141
+ }
142
+ }
143
+
144
+ function confirmationRequired(inputEnded) {
145
+ renderConfirmationRequired(
146
+ buildConfirmationRequiredDiagnostic({
147
+ correlationId: `app_stop_${randomUUID()}`,
148
+ inputEnded,
149
+ retryCommand: `gencow app stop ${name} --yes`,
150
+ subject: `Stopping production app ${name} needs confirmation.`,
151
+ }),
152
+ { errorImpl, logImpl },
153
+ );
154
+ return 1;
155
+ }
156
+
157
+ const result = await mutate(MUTATION[subcmd], { name });
158
+ if (!result) return fail("CLI_PLATFORM_UNREACHABLE");
159
+ const { response, body } = result;
160
+ if (!response.ok) {
161
+ const code = classifyLifecycleFailure(response, body);
162
+ if (code === "APP_ALREADY_RUNNING" && subcmd === "resume") {
163
+ infoImpl(`${name} is already running. Nothing to do.`);
164
+ return 0;
165
+ }
166
+ return fail(code, { correlation: correlationOf(response, body) });
167
+ }
168
+
169
+ if (subcmd !== "stop") {
170
+ if (body?.success === true && body.status === "running") {
171
+ logImpl(`${GREEN} ✓${RESET} ${name} is running.`);
172
+ } else {
173
+ infoImpl(`Request accepted for ${name}. Verify with: gencow app status ${name}`);
174
+ }
175
+ return 0;
176
+ }
177
+
178
+ if (body?.success === true && body.status === "stopped") {
179
+ logImpl(`${GREEN} ✓${RESET} ${name} is stopped. Resume with: gencow app resume ${name}`);
180
+ return 0;
181
+ }
182
+ if (typeof body?.operationId !== "string" || body.operationId.length === 0) {
183
+ infoImpl(`Stop requested for ${name}. Verify with: gencow app status ${name}`);
184
+ return 0;
185
+ }
186
+
187
+ infoImpl(`Stopping ${name}...`);
188
+ const maxPolls = Math.max(1, Math.ceil((args.waitSeconds * 1000) / POLL_INTERVAL_MS));
189
+ for (let poll = 0; poll < maxPolls; poll++) {
190
+ let statusResponse = null;
191
+ try {
192
+ statusResponse = await rpcQueryImpl(creds, "apps.stopStatus", { name, operationId: body.operationId });
193
+ } catch {
194
+ statusResponse = null;
195
+ }
196
+ if (statusResponse?.status === 401) return fail("CLI_AUTH_REQUIRED");
197
+ const status = statusResponse?.ok ? await readBody(statusResponse) : null;
198
+ if (status?.state === "completed") {
199
+ logImpl(`${GREEN} ✓${RESET} ${name} is stopped. Resume with: gencow app resume ${name}`);
200
+ return 0;
201
+ }
202
+ const failureCode = status ? stopFailureCode(status.state) : null;
203
+ if (failureCode) {
204
+ return fail(failureCode, { correlation: correlationOf(statusResponse, status) ?? correlationOf(response, body), extra: stopDiagnosticLines(status.diagnostics) });
205
+ }
206
+ await sleepImpl(POLL_INTERVAL_MS);
207
+ }
208
+ return fail("APP_STOP_PENDING", { correlation: correlationOf(response, body), extra: [`Operation: ${body.operationId}`] });
209
+ };
210
+ }
@@ -0,0 +1,152 @@
1
+ // Pure classification and diagnostics for `gencow app stop|resume|wake`.
2
+ // Server errors are bounded to a fixed catalog: raw server text, paths and role names are never echoed.
3
+
4
+ const SAFE_CORRELATION = /^[A-Za-z0-9_-]{8,128}$/u;
5
+ const SAFE_CODE = /^[A-Z][A-Z0-9_]{2,80}$/u;
6
+ const SAFE_TEXT = /^[A-Za-z0-9 _.,:;()/\-]{1,160}$/u;
7
+
8
+ const isRecord = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
9
+
10
+ /** command-aware next steps use {name}. */
11
+ const CATALOG = {
12
+ APP_NOT_FOUND: {
13
+ message: "App not found in your account.",
14
+ state: "nothing was changed.",
15
+ retry: "no",
16
+ next: "gencow app list",
17
+ },
18
+ APP_NO_BACKEND: {
19
+ message: "This is a static-only app: it has no backend process to stop, resume or wake.",
20
+ state: "nothing was changed; static files keep being served.",
21
+ retry: "no",
22
+ next: "deploy a backend first (gencow deploy), or manage static files with gencow static",
23
+ },
24
+ APP_FROZEN: {
25
+ message: "The app is frozen (archived), so its runtime cannot be controlled.",
26
+ state: "nothing was changed.",
27
+ retry: "after the app is thawed",
28
+ next: "thaw the app from the Gencow dashboard (CLI thaw is not available yet), then retry",
29
+ },
30
+ APP_OWNER_ACCOUNT_HELD: {
31
+ message: "The app is locked because your account has a hold set by Gencow.",
32
+ state: "nothing was changed.",
33
+ retry: "no, not until the hold is lifted",
34
+ next: "open the Gencow dashboard to see the account status; the app can be controlled again once the hold is lifted",
35
+ },
36
+ APP_ALREADY_RUNNING: {
37
+ message: "The app is already running.",
38
+ state: "nothing was changed.",
39
+ retry: "no",
40
+ next: "gencow app status {name}",
41
+ },
42
+ APP_NOT_IDLE: {
43
+ message: "The app is not idle, so there is nothing to wake.",
44
+ state: "nothing was changed.",
45
+ retry: "no",
46
+ next: "gencow app status {name}; if it is stopped use gencow app resume {name}",
47
+ },
48
+ APP_STOP_PENDING: {
49
+ message: "The stop is still in progress; the CLI stopped waiting.",
50
+ state: "the stop continues on the Platform; the app may still be serving.",
51
+ retry: "no, do not start another stop",
52
+ next: "gencow app status {name}",
53
+ },
54
+ APP_STOP_BLOCKED_ACTIVE_WORK: {
55
+ message: "The stop is blocked because the app still has active work.",
56
+ state: "the app keeps serving.",
57
+ retry: "yes, once activity is quiet",
58
+ next: "wait for activity to finish, then run gencow app stop {name} again",
59
+ },
60
+ APP_STOP_OWNERSHIP_UNCONFIRMED: {
61
+ message: "The Platform could not confirm which runtime owns this app, so the stop was not confirmed.",
62
+ state: "unconfirmed; the app may still be running.",
63
+ retry: "no",
64
+ next: "gencow app status {name}",
65
+ },
66
+ APP_STOP_FAILED: {
67
+ message: "The stop did not complete.",
68
+ state: "unknown; check the app status.",
69
+ retry: "yes, after checking",
70
+ next: "gencow app status {name}",
71
+ },
72
+ APP_LIFECYCLE_FAILED: {
73
+ message: "The request could not be completed.",
74
+ state: "unknown; check the app status.",
75
+ retry: "yes, after checking",
76
+ next: "gencow app status {name}",
77
+ },
78
+ CLI_LIFECYCLE_USAGE_INVALID: {
79
+ message: "Missing or invalid arguments.",
80
+ state: "nothing was changed.",
81
+ retry: "yes, with valid arguments",
82
+ next: "gencow app --help",
83
+ },
84
+ CLI_PLATFORM_UNAVAILABLE: {
85
+ message: "The Gencow Platform is temporarily unavailable.",
86
+ state: "nothing was changed.",
87
+ retry: "yes",
88
+ next: "wait a moment, then run the command again",
89
+ },
90
+ CLI_PLATFORM_UNREACHABLE: {
91
+ message: "Could not reach the Gencow Platform.",
92
+ state: "unknown; the request may or may not have been received.",
93
+ retry: "yes, after checking the status",
94
+ next: "gencow app status {name}",
95
+ },
96
+ CLI_AUTH_REQUIRED: {
97
+ message: "You are not signed in, or your session has expired.",
98
+ state: "nothing was changed.",
99
+ retry: "no",
100
+ next: "gencow login",
101
+ },
102
+ };
103
+
104
+ export function classifyLifecycleFailure(response, body) {
105
+ if (isRecord(body) && typeof body.code === "string" && SAFE_CODE.test(body.code) && CATALOG[body.code]) return body.code;
106
+ if (response?.status === 401) return "CLI_AUTH_REQUIRED";
107
+ const message = isRecord(body) && typeof body.error === "string" ? body.error : "";
108
+ if (/not found/iu.test(message)) return "APP_NOT_FOUND";
109
+ if (/no backend/iu.test(message)) return "APP_NO_BACKEND";
110
+ if (/frozen/iu.test(message)) return "APP_FROZEN";
111
+ if (/already running/iu.test(message)) return "APP_ALREADY_RUNNING";
112
+ if (/not idle/iu.test(message)) return "APP_NOT_IDLE";
113
+ if (response?.status === 503) return "CLI_PLATFORM_UNAVAILABLE";
114
+ return "APP_LIFECYCLE_FAILED";
115
+ }
116
+
117
+ export function renderLifecycleFailure(code, { name, correlation, extra } = {}) {
118
+ const entry = CATALOG[code] ?? CATALOG.APP_LIFECYCLE_FAILED;
119
+ const sub = (text) => text.replaceAll("{name}", name ?? "<name>");
120
+ const lines = [entry.message, `Code: ${CATALOG[code] ? code : "APP_LIFECYCLE_FAILED"}`];
121
+ lines.push(`State: ${sub(entry.state)}`, `Retryable: ${entry.retry}`, `Next: ${sub(entry.next)}`);
122
+ for (const line of extra ?? []) lines.push(line);
123
+ if (typeof correlation === "string" && SAFE_CORRELATION.test(correlation)) lines.push(`Correlation: ${correlation}`);
124
+ return lines.join("\n");
125
+ }
126
+
127
+ export function correlationOf(response, body) {
128
+ const fromBody = isRecord(body) && typeof body.correlationId === "string" ? body.correlationId : undefined;
129
+ return fromBody ?? response?.headers?.get?.("x-correlation-id") ?? response?.headers?.get?.("x-request-id") ?? undefined;
130
+ }
131
+
132
+ const STOP_TERMINAL_FAILURE = {
133
+ blocked_active_work: "APP_STOP_BLOCKED_ACTIVE_WORK",
134
+ blocked_ambiguous_binding: "APP_STOP_OWNERSHIP_UNCONFIRMED",
135
+ failed: "APP_STOP_FAILED",
136
+ };
137
+
138
+ export function stopFailureCode(state) {
139
+ return STOP_TERMINAL_FAILURE[state] ?? null;
140
+ }
141
+
142
+ /** Surface the typed diagnostics the Platform already computes (stage, state impact, retry precondition). */
143
+ export function stopDiagnosticLines(diagnostics) {
144
+ if (!isRecord(diagnostics)) return [];
145
+ const safe = (v) => (typeof v === "string" && SAFE_TEXT.test(v) ? v : null);
146
+ const lines = [];
147
+ if (safe(diagnostics.failureStage)) lines.push(`Stage: ${diagnostics.failureStage}`);
148
+ if (safe(diagnostics.stateImpact)) lines.push(`State impact: ${diagnostics.stateImpact}`);
149
+ if (safe(diagnostics.retryPrecondition)) lines.push(`Before retry: ${diagnostics.retryPrecondition}`);
150
+ if (safe(diagnostics.nextAction)) lines.push(`Platform guidance: ${diagnostics.nextAction}`);
151
+ return lines;
152
+ }
@@ -0,0 +1,148 @@
1
+ import {
2
+ filterApps,
3
+ formatCreditsLines,
4
+ formatInvalidResponse,
5
+ formatUnreachable,
6
+ formatUsageFailure,
7
+ formatUsageLines,
8
+ parseUsageMonth,
9
+ parseUsagePayload,
10
+ toCreditsJson,
11
+ toUsageJson,
12
+ } from "./credits-format.mjs";
13
+ import { BOLD, CYAN, DIM, RESET, error, info, log } from "./output.mjs";
14
+ import { requireCreds, rpcQuery } from "./platform-client.mjs";
15
+
16
+ function parseArgs(args, allowed) {
17
+ const flags = { json: false, month: undefined, app: undefined };
18
+ for (let i = 0; i < args.length; i++) {
19
+ const arg = args[i];
20
+ if (arg === "--json") flags.json = true;
21
+ else if (arg === "--prod") continue; // account-level data: environment flag is accepted and ignored
22
+ else if (allowed.includes("month") && (arg === "--month" || arg.startsWith("--month="))) {
23
+ flags.month = arg.includes("=") ? arg.slice("--month=".length) : args[++i];
24
+ if (flags.month === undefined) flags.month = "";
25
+ } else if (allowed.includes("app") && (arg === "--app" || arg === "-a" || arg.startsWith("--app="))) {
26
+ flags.app = arg.includes("=") ? arg.slice("--app=".length) : args[++i];
27
+ if (flags.app === undefined) flags.app = "";
28
+ } else {
29
+ return { error: `Unknown option: ${/^-[-A-Za-z0-9=_]{1,40}$/u.test(arg) ? arg : "(invalid)"}` };
30
+ }
31
+ }
32
+ return flags;
33
+ }
34
+
35
+ async function fetchUsage({ command, month, deps }) {
36
+ const creds = deps.requireCredsImpl();
37
+ let response;
38
+ try {
39
+ response = await deps.rpcQueryImpl(creds, "usage.byUser", month ? { month } : {});
40
+ } catch {
41
+ deps.errorImpl(formatUnreachable({ command }));
42
+ return null;
43
+ }
44
+ const body = await response.json().catch(() => null);
45
+ if (!response.ok) {
46
+ deps.errorImpl(formatUsageFailure(response, body, { command }));
47
+ return null;
48
+ }
49
+ const summary = parseUsagePayload(body);
50
+ if (!summary) {
51
+ deps.errorImpl(formatInvalidResponse({ command }));
52
+ return null;
53
+ }
54
+ return summary;
55
+ }
56
+
57
+ function withDefaults(overrides) {
58
+ return {
59
+ errorImpl: error,
60
+ infoImpl: info,
61
+ logImpl: log,
62
+ requireCredsImpl: requireCreds,
63
+ rpcQueryImpl: rpcQuery,
64
+ nowImpl: () => new Date(),
65
+ ...overrides,
66
+ };
67
+ }
68
+
69
+ function renderHelp(logImpl, command) {
70
+ logImpl(`\n${BOLD}${CYAN}gencow ${command}${RESET}\n`);
71
+ if (command === "credits") {
72
+ logImpl(" Show your credit balance and plan.\n");
73
+ logImpl(" Usage: gencow credits [--json]\n");
74
+ } else {
75
+ logImpl(" Show credit usage by app and service for a month.\n");
76
+ logImpl(" Usage: gencow usage [--month YYYY-MM] [--app <name>] [--json]\n");
77
+ }
78
+ logImpl(` ${DIM}Requires your login session (gencow login). CI deploy tokens cannot read account credits.${RESET}\n`);
79
+ }
80
+
81
+ export function createCreditsCommand(overrides = {}) {
82
+ const deps = withDefaults(overrides);
83
+ return async function credits(...args) {
84
+ if (args.includes("--help") || args.includes("-h")) {
85
+ renderHelp(deps.logImpl, "credits");
86
+ return 0;
87
+ }
88
+ const flags = parseArgs(args, []);
89
+ if (flags.error) {
90
+ deps.errorImpl(`${flags.error}\nUsage: gencow credits [--json]`);
91
+ return 1;
92
+ }
93
+ const summary = await fetchUsage({ command: "credits", month: undefined, deps });
94
+ if (!summary) return 1;
95
+ if (flags.json) {
96
+ deps.logImpl(JSON.stringify(toCreditsJson(summary), null, 2));
97
+ return 0;
98
+ }
99
+ for (const line of formatCreditsLines(summary)) deps.logImpl(line);
100
+ if (summary.serviceCredits.balance <= 0) {
101
+ deps.infoImpl("Service credit balance is 0. Add credits from the Gencow dashboard (Billing) to keep using AI and media features.");
102
+ }
103
+ return 0;
104
+ };
105
+ }
106
+
107
+ export function createUsageCommand(overrides = {}) {
108
+ const deps = withDefaults(overrides);
109
+ return async function usage(...args) {
110
+ if (args.includes("--help") || args.includes("-h")) {
111
+ renderHelp(deps.logImpl, "usage");
112
+ return 0;
113
+ }
114
+ const flags = parseArgs(args, ["month", "app"]);
115
+ if (flags.error) {
116
+ deps.errorImpl(`${flags.error}\nUsage: gencow usage [--month YYYY-MM] [--app <name>] [--json]`);
117
+ return 1;
118
+ }
119
+ const month = parseUsageMonth(flags.month, deps.nowImpl());
120
+ if (!month.ok) {
121
+ deps.errorImpl(`${month.message}\nCode: CLI_USAGE_MONTH_INVALID\nState: nothing was changed.\nNext: gencow usage --month YYYY-MM`);
122
+ return 1;
123
+ }
124
+ if (flags.app === "") {
125
+ deps.errorImpl("Usage: gencow usage --app <name>");
126
+ return 1;
127
+ }
128
+ const summary = await fetchUsage({ command: "usage", month: month.month, deps });
129
+ if (!summary) return 1;
130
+ if (flags.app && filterApps(summary.apps, flags.app).length === 0) {
131
+ const known = summary.apps.map((app) => app.name).join(", ") || "(none)";
132
+ deps.errorImpl(
133
+ `App "${flags.app}" was not found in your account.\nCode: APP_NOT_FOUND\nState: nothing was changed.\nYour apps: ${known}\nNext: gencow app list`,
134
+ );
135
+ return 1;
136
+ }
137
+ if (flags.json) {
138
+ deps.logImpl(JSON.stringify(toUsageJson(summary, flags.app), null, 2));
139
+ return 0;
140
+ }
141
+ for (const line of formatUsageLines(summary, flags.app)) deps.logImpl(line);
142
+ return 0;
143
+ };
144
+ }
145
+
146
+ export function createCreditsCommands(overrides = {}) {
147
+ return { credits: createCreditsCommand(overrides), usage: createUsageCommand(overrides) };
148
+ }