@batadata/cli 0.1.3 → 0.1.5

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/dist/api.js CHANGED
@@ -14,7 +14,7 @@ export async function request(method, path, options = {}) {
14
14
  }
15
15
  const headers = {
16
16
  "Content-Type": "application/json",
17
- "User-Agent": "@batadata/cli 0.1.3",
17
+ "User-Agent": "@batadata/cli 0.1.4",
18
18
  };
19
19
  if (options.token) {
20
20
  headers["Authorization"] = `Bearer ${options.token}`;
@@ -36,26 +36,46 @@ function formatDate(iso) {
36
36
  * when the compute is ready to serve a query without a cold start.
37
37
  */
38
38
  function branchStatusLabel(b) {
39
- const base = b.computeStatus || b.status || "-";
39
+ const base = b.computeStatus || "-";
40
40
  if (b.ready === true)
41
41
  return `${base} ${colors.green("✓")}`;
42
42
  return base;
43
43
  }
44
44
  /**
45
- * Resolve a project's primary branch (the one to run a query against). Lists
46
- * branches the same way `db branches` does (GET /v1/projects/:id) and returns
47
- * the primary, falling back to the first branch. Returns null if the project
48
- * has no branches or the lookup failed.
45
+ * List a project's branches (GET /v1/projects/:id), each enriched by the server
46
+ * with computeStatus + ready. Returns null if the lookup failed.
49
47
  */
50
- async function getPrimaryBranch(projectId, token, teamId) {
48
+ async function listBranches(projectId, token, teamId) {
51
49
  const query = {};
52
50
  if (teamId)
53
51
  query.team_id = teamId;
54
52
  const res = await api.get(`/v1/projects/${projectId}`, token, query);
55
53
  if (!res.ok)
56
54
  return null;
57
- const list = res.data.branches ?? [];
58
- return list.find((b) => b.is_primary) ?? list[0] ?? null;
55
+ return { branches: res.data.branches ?? [], projectName: res.data.name };
56
+ }
57
+ /**
58
+ * Resolve a project's primary branch (the one to run a query against), falling
59
+ * back to the first branch. Returns null if the project has no branches or the
60
+ * lookup failed.
61
+ */
62
+ async function getPrimaryBranch(projectId, token, teamId) {
63
+ const result = await listBranches(projectId, token, teamId);
64
+ if (!result)
65
+ return null;
66
+ return result.branches.find((b) => b.isPrimary) ?? result.branches[0] ?? null;
67
+ }
68
+ /**
69
+ * Resolve a `--branch` reference — which may be a branch ID **or** a branch
70
+ * name — to a concrete branch. Agents naturally pass the name (the same string
71
+ * they used with `db branch create`), so accepting only an id was a footgun
72
+ * ("Branch not found"). Returns null if no branch matches.
73
+ */
74
+ async function resolveBranchRef(projectId, token, teamId, ref) {
75
+ const result = await listBranches(projectId, token, teamId);
76
+ if (!result)
77
+ return null;
78
+ return result.branches.find((b) => b.id === ref || b.name === ref) ?? null;
59
79
  }
60
80
  export async function connect() {
61
81
  // psql is an interactive session — there's no headless equivalent. Don't spawn
@@ -123,38 +143,31 @@ export async function branches() {
123
143
  emitError("NO_PROJECT", "No default project set.", "Set one with: bata projects info <id>");
124
144
  }
125
145
  const s = jsonMode ? null : spinner("Fetching branches");
126
- const query = {};
127
- if (config.defaultTeam)
128
- query.team_id = config.defaultTeam;
129
- const res = await api.get(`/v1/projects/${projectId}`, token, query);
146
+ const result = await listBranches(projectId, token, config.defaultTeam);
130
147
  s?.stop();
131
- if (!res.ok) {
132
- emitError(res.status === 401 || res.status === 403 ? "INVALID_KEY"
133
- : res.status === 404 ? "NO_PROJECT"
134
- : res.status >= 500 || res.status === 0 ? "API_UNAVAILABLE"
135
- : "CLI_ERROR", apiError(res, "Failed to fetch branches"), "");
148
+ if (!result) {
149
+ emitError("API_UNAVAILABLE", "Failed to fetch branches.", "");
136
150
  }
137
- const branchList = res.data.branches || [];
151
+ const branchList = result.branches;
138
152
  if (jsonMode) {
139
153
  json({
140
154
  project_id: projectId,
141
- project_name: res.data.name,
155
+ project_name: result.projectName,
142
156
  branches: branchList.map((b) => ({
143
157
  id: b.id,
144
158
  name: b.name,
145
- is_primary: b.is_primary,
146
- status: b.status,
159
+ is_primary: b.isPrimary ?? false,
147
160
  // Compute readiness — what agents poll on between a create/cold start
148
161
  // and a successful query.
149
162
  computeStatus: b.computeStatus ?? null,
150
163
  ready: b.ready ?? null,
151
- created_at: b.created_at,
164
+ created_at: b.createdAt ?? null,
152
165
  })),
153
166
  count: branchList.length,
154
167
  });
155
168
  return;
156
169
  }
157
- heading(`Branches — ${res.data.name}`);
170
+ heading(`Branches — ${result.projectName}`);
158
171
  if (branchList.length === 0) {
159
172
  log(` ${colors.dim("No branches found.")}`);
160
173
  log();
@@ -162,11 +175,11 @@ export async function branches() {
162
175
  }
163
176
  table(["NAME", "PRIMARY", "STATUS", "CREATED"], branchList.map((b) => [
164
177
  b.name,
165
- b.is_primary ? colors.green("yes") : "-",
166
- // Prefer the live compute lifecycle (computeStatus); fall back to the
167
- // branch row status. Mark ready with a check so the column is scannable.
178
+ b.isPrimary ? colors.green("yes") : "-",
179
+ // Live compute lifecycle (computeStatus), with a check once ready so the
180
+ // column is scannable.
168
181
  branchStatusLabel(b),
169
- formatDate(b.created_at),
182
+ formatDate(b.createdAt ?? ""),
170
183
  ]));
171
184
  log();
172
185
  }
@@ -275,10 +288,11 @@ export async function studio() {
275
288
  openBrowser(studioUrl);
276
289
  }
277
290
  /**
278
- * Pull a `--branch <id>` / `--branch=<id>` flag out of the query args and return
279
- * the explicit branch id (if any) plus the remaining args, which join into the
280
- * SQL string. Keeps `db query` order-independent (the flag can sit before or
281
- * after the SQL) and consistent with how global flags are parsed.
291
+ * Pull a `--branch <ref>` / `--branch=<ref>` flag out of the query args and
292
+ * return the explicit branch ref an id OR a name, resolved later plus the
293
+ * remaining args, which join into the SQL string. Keeps `db query`
294
+ * order-independent (the flag can sit before or after the SQL) and consistent
295
+ * with how global flags are parsed.
282
296
  */
283
297
  function parseBranchFlag(args) {
284
298
  let branchId;
@@ -311,11 +325,22 @@ export async function query(args = []) {
311
325
  emitError("NO_PROJECT", "No default project set.", "Set one with: bata projects info <id>");
312
326
  }
313
327
  const s = jsonMode ? null : spinner("Running query");
314
- // Target branch: an explicit --branch <id> wins; otherwise resolve the
315
- // project's primary branch. /v1/sql/execute is keyed on branch_id, not
316
- // project. (The old code POSTed to /v1/query/:projectId, which 404s.)
317
- let branchId_ = branchId;
318
- if (!branchId_) {
328
+ // Target branch: an explicit --branch <id-or-name> wins; otherwise resolve
329
+ // the project's primary branch. /v1/sql/execute is keyed on branch_id, not
330
+ // project. (The old code POSTed to /v1/query/:projectId, which 404s.) We
331
+ // resolve the --branch value against the project's branch list so a NAME
332
+ // works too — sending a name straight through as branch_id 404'd ("Branch
333
+ // not found").
334
+ let branchId_;
335
+ if (branchId) {
336
+ const branch = await resolveBranchRef(projectId, token, config.defaultTeam, branchId);
337
+ if (!branch) {
338
+ s?.stop();
339
+ emitError("BRANCH_NOT_FOUND", `Branch "${branchId}" not found in this project.`, "List branches with: bata db branches --json");
340
+ }
341
+ branchId_ = branch.id;
342
+ }
343
+ else {
319
344
  const branch = await getPrimaryBranch(projectId, token, config.defaultTeam);
320
345
  if (!branch) {
321
346
  s?.stop();
@@ -401,9 +426,9 @@ function dbHelp(sub) {
401
426
  log(` ${colors.bold("bata db query")} — run a SQL query against a branch`);
402
427
  log();
403
428
  usage('bata db query "SELECT 1"');
404
- usage("bata db query <sql> [--branch <branch_id>] [--json]");
429
+ usage("bata db query <sql> [--branch <id-or-name>] [--json]");
405
430
  log();
406
- note("--branch <branch_id> Target a specific branch (default: the project's primary)");
431
+ note("--branch <id-or-name> Target a specific branch by id OR name (default: the project's primary)");
407
432
  note("--json Emit rows as JSON objects + row_count");
408
433
  note("Cold-start note: a just-created/idle branch may answer with exit 6");
409
434
  note("(retryable) while its compute wakes — retry in a few seconds.");
@@ -447,7 +472,7 @@ function dbHelp(sub) {
447
472
  usage("bata db branch create Create a new branch");
448
473
  usage("bata db branch delete Delete a branch");
449
474
  usage("bata db studio Open the table browser");
450
- usage("bata db query <sql> Run a SQL query (--branch <id> to target a branch)");
475
+ usage("bata db query <sql> Run a SQL query (--branch <id-or-name> to target a branch)");
451
476
  log();
452
477
  note("Add --help to any subcommand for details (e.g. bata db query --help).");
453
478
  }
@@ -4,7 +4,7 @@ export async function dev() {
4
4
  log(` Get started with BataDB in your project:`);
5
5
  log();
6
6
  log(` ${colors.cyan("1.")} ${colors.bold("Install the ORM")}`);
7
- log(` ${colors.dim("npm install @batadata/turbine")}`);
7
+ log(` ${colors.dim("npm install turbine-orm")}`);
8
8
  log();
9
9
  log(` ${colors.cyan("2.")} ${colors.bold("Set your database URL")}`);
10
10
  log(` ${colors.dim("Add DATABASE_URL to your .env file:")}`);
@@ -14,10 +14,16 @@ export async function dev() {
14
14
  log(` ${colors.dim("bata generate")}`);
15
15
  log();
16
16
  log(` ${colors.cyan("4.")} ${colors.bold("Import and query")}`);
17
- log(` ${colors.dim("import { turbine } from '@batadata/turbine'")}`);
18
- log(` ${colors.dim("const db = turbine('DATABASE_URL')")}`);
17
+ log(` ${colors.dim("import { turbine } from './generated/turbine'")}`);
18
+ log(` ${colors.dim("const db = turbine({ connectionString: process.env.DATABASE_URL })")}`);
19
19
  log(` ${colors.dim("const users = await db.users.findMany()")}`);
20
20
  log();
21
+ log(` ${colors.dim("On the edge? Bind BataDB's HTTP driver to Turbine with zero glue:")}`);
22
+ log(` ${colors.dim("import { turbineHttp } from 'turbine-orm/serverless'")}`);
23
+ log(` ${colors.dim("import { Pool } from '@batadata/serverless'")}`);
24
+ log(` ${colors.dim("import { SCHEMA } from './generated/turbine/metadata.js'")}`);
25
+ log(` ${colors.dim("const db = turbineHttp(new Pool({ connectionString: process.env.DATABASE_URL }), SCHEMA)")}`);
26
+ log();
21
27
  log(` ${colors.bold("Useful commands:")}`);
22
28
  log(` ${colors.cyan("bata db connect")} Open psql shell`);
23
29
  log(` ${colors.cyan("bata db studio")} Open visual table browser`);
@@ -4,21 +4,21 @@ function printHelp() {
4
4
  log();
5
5
  log(` ${colors.bold("bata generate")} ${colors.dim("— generate types from your database schema")}`);
6
6
  log();
7
- log(` Runs the Turbine type generator (${colors.dim("@batadata/turbine")}) against your`);
7
+ log(` Runs the Turbine type generator (${colors.dim("turbine-orm")}) against your`);
8
8
  log(` database, producing typed query bindings.`);
9
9
  log();
10
10
  log(` ${colors.bold("Options")}`);
11
11
  log(` ${colors.dim("--watch, -w")} Regenerate on schema changes`);
12
12
  log(` ${colors.dim("--help, -h")} Show this help`);
13
13
  log();
14
- log(` ${colors.dim("Requires @batadata/turbine. Install with:")} ${colors.cyan("npm install @batadata/turbine")}`);
14
+ log(` ${colors.dim("Requires turbine-orm. Install with:")} ${colors.cyan("npm install turbine-orm")}`);
15
15
  log();
16
16
  }
17
17
  /**
18
18
  * Resolve a runnable Turbine binary without invoking the network.
19
- * Prefers a locally installed binary; falls back to none (we do NOT
20
- * silently shell out to `npx`, which would try to download an unpublished
21
- * package and hang/crash).
19
+ * Prefers a locally installed binary (the `turbine` bin shipped by the
20
+ * `turbine-orm` package); falls back to a global install on PATH. We do NOT
21
+ * silently shell out to `npx`, which would trigger a download/prompt.
22
22
  */
23
23
  function resolveTurbine() {
24
24
  // 1. Local node_modules binary
@@ -46,10 +46,11 @@ export async function generate(args) {
46
46
  if (!turbine) {
47
47
  error("Turbine is not installed.");
48
48
  log();
49
- log(` ${colors.dim("`bata generate` uses the Turbine type generator, which is not")}`);
50
- log(` ${colors.dim("bundled with the CLI. Install it in your project first:")}`);
49
+ log(` ${colors.dim("`bata generate` uses the Turbine type generator (the `turbine` bin")}`);
50
+ log(` ${colors.dim("from turbine-orm), which is not bundled with the CLI. Install it")}`);
51
+ log(` ${colors.dim("in your project first:")}`);
51
52
  log();
52
- log(` ${colors.cyan("npm install @batadata/turbine")}`);
53
+ log(` ${colors.cyan("npm install turbine-orm")}`);
53
54
  log();
54
55
  log(` ${colors.dim("Then run")} ${colors.cyan("bata generate")} ${colors.dim("again.")}`);
55
56
  log();
@@ -71,7 +72,7 @@ export async function generate(args) {
71
72
  });
72
73
  child.on("error", (err) => {
73
74
  warn(`Failed to run turbine generate: ${err.message}`);
74
- error("Make sure @batadata/turbine is installed and on your PATH.");
75
+ error("Make sure turbine-orm is installed and its `turbine` bin is on your PATH.");
75
76
  process.exit(1);
76
77
  });
77
78
  child.on("exit", (code) => {
package/dist/config.js CHANGED
@@ -1,7 +1,18 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import * as os from "node:os";
4
- const CONFIG_PATH = path.join(os.homedir(), ".batarc");
4
+ /**
5
+ * Resolve the `~/.batarc` path at CALL time, not import time. Reading
6
+ * `os.homedir()` once into a top-level const freezes the home directory before
7
+ * anything can override HOME — which silently breaks (a) users who set a custom
8
+ * HOME and (b) tests that redirect HOME to a temp dir (the redirect would be
9
+ * ignored and the suite would read the developer's REAL ~/.batarc). Preferring
10
+ * the env vars makes the override deterministic across platforms.
11
+ */
12
+ function configPath() {
13
+ const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
14
+ return path.join(home, ".batarc");
15
+ }
5
16
  const DEFAULT_API_URL = "https://api.batadata.com";
6
17
  const runtime = { json: false, yes: false };
7
18
  export function setRuntime(ctx) {
@@ -23,7 +34,7 @@ export function isYes() {
23
34
  }
24
35
  export function loadConfig() {
25
36
  try {
26
- const raw = fs.readFileSync(CONFIG_PATH, "utf-8");
37
+ const raw = fs.readFileSync(configPath(), "utf-8");
27
38
  return JSON.parse(raw);
28
39
  }
29
40
  catch {
@@ -33,11 +44,11 @@ export function loadConfig() {
33
44
  export function saveConfig(config) {
34
45
  const existing = loadConfig();
35
46
  const merged = { ...existing, ...config };
36
- fs.writeFileSync(CONFIG_PATH, JSON.stringify(merged, null, 2) + "\n", "utf-8");
47
+ fs.writeFileSync(configPath(), JSON.stringify(merged, null, 2) + "\n", "utf-8");
37
48
  }
38
49
  export function clearConfig() {
39
50
  try {
40
- fs.unlinkSync(CONFIG_PATH);
51
+ fs.unlinkSync(configPath());
41
52
  }
42
53
  catch {
43
54
  // File doesn't exist, that's fine
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import { parseGlobalFlags } from "./args.js";
15
15
  import { isJsonMode } from "./config.js";
16
16
  import { colors, log, banner } from "./utils/logger.js";
17
17
  import { exitCodeFor, isRetryable } from "./utils/errors.js";
18
- const VERSION = "0.1.3";
18
+ const VERSION = "0.1.4";
19
19
  function help() {
20
20
  banner();
21
21
  log(` ${colors.bold("Usage")}`);
@@ -124,6 +124,6 @@ export function kvList(items) {
124
124
  // Banner
125
125
  export function banner() {
126
126
  log();
127
- log(` ${colors.cyan(colors.bold("BataDB"))} ${colors.dim("v0.1.3")} ${colors.dim("— serverless Postgres platform")}`);
127
+ log(` ${colors.cyan(colors.bold("BataDB"))} ${colors.dim("v0.1.4")} ${colors.dim("— serverless Postgres platform")}`);
128
128
  log();
129
129
  }
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@batadata/cli",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "CLI for BataDB — serverless Postgres platform",
5
5
  "bin": {
6
6
  "bata": "./dist/index.js"
7
7
  },
8
8
  "type": "module",
9
9
  "scripts": {
10
- "build": "tsc",
11
- "dev": "tsc --watch",
10
+ "build": "tsc -p tsconfig.build.json",
11
+ "dev": "tsc -p tsconfig.build.json --watch",
12
+ "typecheck": "tsc --noEmit",
12
13
  "test": "vitest run"
13
14
  },
14
15
  "engines": {
@@ -1 +0,0 @@
1
- export {};
@@ -1,173 +0,0 @@
1
- import * as fs from "node:fs";
2
- import * as os from "node:os";
3
- import * as path from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- const { get, post } = vi.hoisted(() => ({
6
- get: vi.fn(async () => ({
7
- ok: true,
8
- status: 200,
9
- data: { id: "proj_1", name: "demo", branches: [{ id: "br_primary", name: "main", is_primary: true, status: "ready" }] },
10
- })),
11
- post: vi.fn(async () => ({ ok: true, status: 200, data: { columns: ["n"], rows: [{ n: "1" }], rowCount: 1 } })),
12
- }));
13
- vi.mock("../api.js", () => ({
14
- api: { get, post, del: vi.fn() },
15
- resolveTeamId: vi.fn(async () => "team_test"),
16
- // Mirror the real apiError so retryable mapping (which reads the server code)
17
- // gets a realistic message; we don't need its exact format here.
18
- apiError: (res, fallback) => {
19
- const msg = res?.data?.error ?? fallback;
20
- const code = res?.data?.code ? ` (${res.data.code})` : "";
21
- return `${msg}${code}`;
22
- },
23
- asList: (data) => (Array.isArray(data) ? data : []),
24
- }));
25
- import { query, handleDb } from "./db.js";
26
- import { setRuntime } from "../config.js";
27
- let tmpHome;
28
- let logSpy;
29
- // process.exit must NOT actually exit the test runner. Throw a tagged error so
30
- // the handler unwinds at the exit point; tests catch it and read the code.
31
- class ExitError extends Error {
32
- code;
33
- constructor(code) {
34
- super(`exit ${code}`);
35
- this.code = code;
36
- }
37
- }
38
- beforeEach(() => {
39
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "bata-cli-db-test-"));
40
- vi.stubEnv("HOME", tmpHome);
41
- vi.stubEnv("USERPROFILE", tmpHome);
42
- // A real credential + a default project so query() reaches the network seam.
43
- fs.writeFileSync(path.join(tmpHome, ".batarc"), JSON.stringify({ defaultProject: "proj_1" }));
44
- setRuntime({ apiKey: "test-token", apiUrl: "https://api.test.local", json: true, yes: false });
45
- get.mockClear();
46
- post.mockClear();
47
- vi.spyOn(process, "exit").mockImplementation(((code) => {
48
- throw new ExitError(code ?? 0);
49
- }));
50
- // Silence the JSON/decorative output so test logs stay clean.
51
- logSpy = vi.spyOn(console, "log").mockImplementation(() => { });
52
- vi.spyOn(console, "error").mockImplementation(() => { });
53
- });
54
- afterEach(() => {
55
- vi.unstubAllEnvs();
56
- vi.restoreAllMocks();
57
- setRuntime({ json: false, yes: false });
58
- fs.rmSync(tmpHome, { recursive: true, force: true });
59
- });
60
- /** Run a handler that's expected to call process.exit; return the exit code. */
61
- async function exitCodeOf(run) {
62
- try {
63
- await run();
64
- }
65
- catch (e) {
66
- if (e instanceof ExitError)
67
- return e.code;
68
- throw e;
69
- }
70
- return 0; // handler returned without exiting (success path)
71
- }
72
- describe("db query — --help short-circuits before any network call", () => {
73
- it("`db query --help` prints help and makes NO api call (exit 0)", async () => {
74
- const code = await exitCodeOf(() => handleDb(["query", "--help"]));
75
- expect(post).not.toHaveBeenCalled();
76
- expect(get).not.toHaveBeenCalled();
77
- expect(code).toBe(0);
78
- // It actually printed usage, not a row result.
79
- const printed = logSpy.mock.calls.map((c) => String(c[0])).join("\n");
80
- expect(printed).toContain("bata db query");
81
- expect(printed).toContain("--branch");
82
- });
83
- it("`db query -h` (short flag) also short-circuits with no api call", async () => {
84
- const code = await exitCodeOf(() => handleDb(["query", "-h"]));
85
- expect(post).not.toHaveBeenCalled();
86
- expect(get).not.toHaveBeenCalled();
87
- expect(code).toBe(0);
88
- });
89
- it("`db --help` prints general db help with no api call", async () => {
90
- const code = await exitCodeOf(() => handleDb(["--help"]));
91
- expect(post).not.toHaveBeenCalled();
92
- expect(get).not.toHaveBeenCalled();
93
- expect(code).toBe(0);
94
- });
95
- });
96
- describe("db query — branch targeting", () => {
97
- it("--branch <id> sets branch_id in the request body and skips primary lookup", async () => {
98
- await exitCodeOf(() => query(["SELECT 1", "--branch", "br_explicit"]));
99
- expect(post).toHaveBeenCalledTimes(1);
100
- expect(post).toHaveBeenCalledWith("/v1/sql/execute", expect.objectContaining({ branch_id: "br_explicit", query: "SELECT 1" }), "test-token");
101
- // Explicit branch → no need to resolve the primary.
102
- expect(get).not.toHaveBeenCalled();
103
- });
104
- it("--branch=<id> (equals form) is also honored", async () => {
105
- await exitCodeOf(() => query(["--branch=br_eq", "SELECT 2"]));
106
- expect(post).toHaveBeenCalledWith("/v1/sql/execute", expect.objectContaining({ branch_id: "br_eq", query: "SELECT 2" }), "test-token");
107
- });
108
- it("without --branch, resolves the project's primary branch (default behavior)", async () => {
109
- await exitCodeOf(() => query(["SELECT 1"]));
110
- expect(get).toHaveBeenCalledTimes(1); // resolved primary
111
- expect(post).toHaveBeenCalledWith("/v1/sql/execute", expect.objectContaining({ branch_id: "br_primary", query: "SELECT 1" }), "test-token");
112
- });
113
- });
114
- describe("db query — retryable cold-start mapping (exit 6)", () => {
115
- it("503 + { code: COMPUTE_STARTING } maps to exit 6 (retryable), not 1", async () => {
116
- post.mockResolvedValueOnce({
117
- ok: false,
118
- status: 503,
119
- data: { error: "compute is starting", code: "COMPUTE_STARTING" },
120
- });
121
- const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
122
- expect(code).toBe(6);
123
- });
124
- it("REGRESSION GUARD: a non-5xx status carrying { code: COMPUTE_STARTING } still maps to exit 6", async () => {
125
- // The pre-fix code only looked at the HTTP status (>=500 || 0), so a
126
- // COMPUTE_STARTING surfaced on, say, a 425 would have been CLI_ERROR (exit
127
- // 1). This is the exact guard for the body-code inspection.
128
- post.mockResolvedValueOnce({
129
- ok: false,
130
- status: 425,
131
- data: { error: "compute is starting", code: "COMPUTE_STARTING" },
132
- });
133
- const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
134
- expect(code).toBe(6);
135
- });
136
- it("a connection-refused error body maps to exit 6", async () => {
137
- post.mockResolvedValueOnce({
138
- ok: false,
139
- status: 0,
140
- data: { error: "connect ECONNREFUSED 127.0.0.1:5432" },
141
- });
142
- const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
143
- expect(code).toBe(6);
144
- });
145
- it("a generic 5xx maps to exit 6", async () => {
146
- post.mockResolvedValueOnce({ ok: false, status: 502, data: { error: "bad gateway" } });
147
- const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
148
- expect(code).toBe(6);
149
- });
150
- it("a genuine SQL syntax error (200 with error field) stays exit 1, NOT retryable", async () => {
151
- post.mockResolvedValueOnce({
152
- ok: true,
153
- status: 200,
154
- data: { error: 'syntax error at or near "SELCT"' },
155
- });
156
- const code = await exitCodeOf(() => query(["SELCT 1", "--branch", "br_ok"]));
157
- expect(code).toBe(1);
158
- });
159
- it("a 400 bad-input SQL error stays exit 1, NOT retryable", async () => {
160
- post.mockResolvedValueOnce({
161
- ok: false,
162
- status: 400,
163
- data: { error: "relation does not exist" },
164
- });
165
- const code = await exitCodeOf(() => query(["SELECT * FROM nope", "--branch", "br_ok"]));
166
- expect(code).toBe(1);
167
- });
168
- it("a 401 stays auth (exit 4), not retryable", async () => {
169
- post.mockResolvedValueOnce({ ok: false, status: 401, data: { error: "invalid key" } });
170
- const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_ok"]));
171
- expect(code).toBe(4);
172
- });
173
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,104 +0,0 @@
1
- import * as fs from "node:fs";
2
- import * as os from "node:os";
3
- import * as path from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- // --- Mock the network layer so no real HTTP happens and we can assert that the
6
- // --- DELETE call is (or isn't) invoked. This is the seam: deleteProject() calls
7
- // --- `api.del(...)`, so a spy here proves whether the delete actually proceeds.
8
- // `vi.hoisted` so the spy exists before the hoisted vi.mock factory runs.
9
- const { del, readlineQuestion } = vi.hoisted(() => ({
10
- del: vi.fn(async () => ({ ok: true, status: 200, data: {} })),
11
- // The interactive prompt seam: confirm() -> prompt() -> readline.question().
12
- // Default answer is empty; a TTY test sets it to "n" to decline.
13
- readlineQuestion: vi.fn((_q, cb) => cb("")),
14
- }));
15
- vi.mock("../api.js", () => ({
16
- api: {
17
- get: vi.fn(async () => ({ ok: true, status: 200, data: {} })),
18
- post: vi.fn(async () => ({ ok: true, status: 200, data: {} })),
19
- del,
20
- },
21
- // No real /v1/teams round-trip; deleteProject only needs an optional team id.
22
- resolveTeamId: vi.fn(async () => "team_test"),
23
- apiError: (_res, fallback) => fallback,
24
- asList: (data) => (Array.isArray(data) ? data : []),
25
- }));
26
- // Mock readline so the interactive confirm() branch never blocks on real stdin.
27
- vi.mock("node:readline", () => ({
28
- default: { createInterface: () => ({ question: readlineQuestion, close: () => { } }) },
29
- createInterface: () => ({ question: readlineQuestion, close: () => { } }),
30
- }));
31
- // We deliberately do NOT mock ../config.js or ../utils/prompts.js — the whole
32
- // point of this test is to exercise the REAL confirmDestructive() + the REAL
33
- // runtime flag plumbing (setRuntime/isYes/isJsonMode), since that branch is the
34
- // destructive-headless contract under test.
35
- import { deleteProject } from "./projects.js";
36
- import { setRuntime } from "../config.js";
37
- let tmpHome;
38
- let realIsTTY;
39
- beforeEach(() => {
40
- // Point ~/.batarc at a throwaway HOME so loadConfig/saveConfig never touch the
41
- // developer's real config. os.homedir() reads HOME at call time (verified).
42
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "bata-cli-test-"));
43
- vi.stubEnv("HOME", tmpHome);
44
- vi.stubEnv("USERPROFILE", tmpHome); // Windows parity
45
- // requireToken() resolves the --api-key runtime value first, so a real
46
- // credential exists without writing a config file.
47
- setRuntime({ apiKey: "test-token", apiUrl: "https://api.test.local", json: false, yes: false });
48
- del.mockClear();
49
- readlineQuestion.mockClear();
50
- readlineQuestion.mockImplementation((_q, cb) => cb(""));
51
- // Snapshot isTTY so individual tests can override it and we restore after.
52
- realIsTTY = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");
53
- });
54
- afterEach(() => {
55
- vi.unstubAllEnvs();
56
- vi.restoreAllMocks();
57
- setRuntime({ json: false, yes: false });
58
- if (realIsTTY) {
59
- Object.defineProperty(process.stdin, "isTTY", realIsTTY);
60
- }
61
- fs.rmSync(tmpHome, { recursive: true, force: true });
62
- });
63
- function setTTY(value) {
64
- Object.defineProperty(process.stdin, "isTTY", { value, configurable: true });
65
- }
66
- describe("projects delete — destructive headless contract", () => {
67
- it("REGRESSION GUARD: with --yes, does NOT prompt and the DELETE actually proceeds", async () => {
68
- // The original bug: headless `--yes` exited 0 having deleted NOTHING.
69
- // This is the exact guard — if deleteProject silently skipped the delete,
70
- // `del` would never be called and this expectation would fail.
71
- setTTY(true); // even on a TTY, --yes must skip the prompt and proceed
72
- setRuntime({ yes: true });
73
- await deleteProject("proj_123");
74
- expect(del).toHaveBeenCalledTimes(1);
75
- expect(del).toHaveBeenCalledWith("/v1/projects/proj_123", "test-token", expect.objectContaining({ team_id: "team_test" }));
76
- });
77
- it("in --json mode, proceeds without prompting and deletes", async () => {
78
- setTTY(true);
79
- setRuntime({ json: true });
80
- await deleteProject("proj_json");
81
- expect(del).toHaveBeenCalledTimes(1);
82
- expect(del).toHaveBeenCalledWith("/v1/projects/proj_json", "test-token", expect.anything());
83
- });
84
- it("when stdin is not a TTY (agent / piped / CI), proceeds and deletes without --yes", async () => {
85
- // This is the CLI's whole purpose: unattended deletes must go through.
86
- setTTY(false);
87
- setRuntime({ yes: false, json: false });
88
- await deleteProject("proj_pipe");
89
- expect(del).toHaveBeenCalledTimes(1);
90
- expect(del).toHaveBeenCalledWith("/v1/projects/proj_pipe", "test-token", expect.anything());
91
- });
92
- it("interactive TTY without --yes WOULD prompt; answering no aborts (no DELETE)", async () => {
93
- // Covers the interactive branch of confirmDestructive(): it must ask, and a
94
- // "no" answer must NOT call the delete API. The mocked readline (above) is
95
- // the seam confirm() -> prompt() uses; we answer "n" to decline.
96
- setTTY(true);
97
- setRuntime({ yes: false, json: false });
98
- readlineQuestion.mockImplementation((_q, cb) => cb("n"));
99
- await deleteProject("proj_keep");
100
- expect(readlineQuestion).toHaveBeenCalledTimes(1); // it DID prompt
101
- expect(readlineQuestion.mock.calls[0][0]).toContain("Delete project");
102
- expect(del).not.toHaveBeenCalled(); // declined → no destructive call
103
- });
104
- });