Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions __tests__/commands/accounts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";

vi.mock("../../src/client.js", () => ({
get: vi.fn(),
post: vi.fn(),
del: vi.fn(),
}));

import { accountsCommand } from "../../src/commands/accounts.js";
import { post } from "../../src/client.js";

let logSpy: ReturnType<typeof vi.spyOn>;
let errorSpy: ReturnType<typeof vi.spyOn>;
let exitSpy: ReturnType<typeof vi.spyOn>;

beforeEach(() => {
logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
exitSpy = vi
.spyOn(process, "exit")
.mockImplementation(() => undefined as never);
});

afterEach(() => {
vi.restoreAllMocks();
});

describe("accounts create", () => {
it("creates account with email and prints account_id", async () => {
vi.mocked(post).mockResolvedValue({
data: { account_id: "acc-123", email: "test@example.com" },
});

await accountsCommand.parseAsync(
["create", "--email", "test@example.com"],
{ from: "user" },
);

expect(post).toHaveBeenCalledWith("/api/accounts", {
email: "test@example.com",
});
expect(logSpy).toHaveBeenCalledWith("acc-123");
});

it("creates account with wallet and prints account_id", async () => {
vi.mocked(post).mockResolvedValue({
data: { account_id: "acc-456", wallet: "0xabc123" },
});

await accountsCommand.parseAsync(
["create", "--wallet", "0xabc123"],
{ from: "user" },
);

expect(post).toHaveBeenCalledWith("/api/accounts", {
wallet: "0xabc123",
});
expect(logSpy).toHaveBeenCalledWith("acc-456");
});

it("prints JSON with --json flag", async () => {
const response = {
data: { account_id: "acc-123", email: "test@example.com" },
};
vi.mocked(post).mockResolvedValue(response);

await accountsCommand.parseAsync(
["create", "--email", "test@example.com", "--json"],
{ from: "user" },
);

expect(logSpy).toHaveBeenCalledWith(JSON.stringify(response, null, 2));
});

it("prints error when no email or wallet provided", async () => {
await accountsCommand.parseAsync(["create"], { from: "user" });

expect(errorSpy).toHaveBeenCalledWith(
"Error: at least one of --email or --wallet is required",
);
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("prints error when account_id is missing from response", async () => {
vi.mocked(post).mockResolvedValue({ data: {} });

await accountsCommand.parseAsync(
["create", "--email", "test@example.com"],
{ from: "user" },
);

expect(errorSpy).toHaveBeenCalledWith(
"Error: Account ID not found in API response",
);
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("prints error on API failure", async () => {
vi.mocked(post).mockRejectedValue(new Error("Request failed"));

await accountsCommand.parseAsync(
["create", "--email", "test@example.com"],
{ from: "user" },
);

expect(errorSpy).toHaveBeenCalledWith("Error: Request failed");
expect(exitSpy).toHaveBeenCalledWith(1);
});
});

describe("accounts upgrade", () => {
it("prints the upgrade URL", async () => {
await accountsCommand.parseAsync(["upgrade"], { from: "user" });

expect(logSpy).toHaveBeenCalledWith(
"To upgrade to Pro, visit: https://chat.recoupable.com/settings",
);
});
});
172 changes: 172 additions & 0 deletions __tests__/commands/keys.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";

vi.mock("../../src/client.js", () => ({
get: vi.fn(),
post: vi.fn(),
del: vi.fn(),
}));

import { keysCommand } from "../../src/commands/keys.js";
import { get, post, del } from "../../src/client.js";

let logSpy: ReturnType<typeof vi.spyOn>;
let errorSpy: ReturnType<typeof vi.spyOn>;
let exitSpy: ReturnType<typeof vi.spyOn>;

beforeEach(() => {
logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
exitSpy = vi
.spyOn(process, "exit")
.mockImplementation(() => undefined as never);
});

afterEach(() => {
vi.restoreAllMocks();
});

describe("keys list", () => {
it("prints API keys table", async () => {
vi.mocked(get).mockResolvedValue({
keys: [
{ id: "key-1", name: "My Key", created_at: "2024-01-01T00:00:00Z", last_used: null },
{ id: "key-2", name: "CI Key", created_at: "2024-02-01T00:00:00Z", last_used: "2024-03-01T00:00:00Z" },
],
});

await keysCommand.parseAsync(["list"], { from: "user" });

expect(get).toHaveBeenCalledWith("/api/keys");
expect(logSpy).toHaveBeenCalledTimes(4); // header + separator + 2 rows
});

it("prints JSON with --json flag", async () => {
const keys = [
{ id: "key-1", name: "My Key", created_at: "2024-01-01T00:00:00Z", last_used: null },
];
vi.mocked(get).mockResolvedValue({ keys });

await keysCommand.parseAsync(["list", "--json"], { from: "user" });

expect(logSpy).toHaveBeenCalledWith(JSON.stringify(keys, null, 2));
});

it("handles empty key list", async () => {
vi.mocked(get).mockResolvedValue({ keys: [] });

await keysCommand.parseAsync(["list"], { from: "user" });

expect(logSpy).toHaveBeenCalledWith("No results.");
});

it("prints error on failure", async () => {
vi.mocked(get).mockRejectedValue(new Error("Unauthorized"));

await keysCommand.parseAsync(["list"], { from: "user" });

expect(errorSpy).toHaveBeenCalledWith("Error: Unauthorized");
expect(exitSpy).toHaveBeenCalledWith(1);
});
});

describe("keys create", () => {
it("creates an API key and prints it", async () => {
vi.mocked(post).mockResolvedValue({ key: "recoup_sk_abc123" });

await keysCommand.parseAsync(["create", "--name", "My Key"], {
from: "user",
});

expect(post).toHaveBeenCalledWith("/api/keys", { key_name: "My Key" });
expect(logSpy).toHaveBeenCalledWith("recoup_sk_abc123");
});

it("prints JSON with --json flag", async () => {
const response = { key: "recoup_sk_abc123" };
vi.mocked(post).mockResolvedValue(response);

await keysCommand.parseAsync(["create", "--name", "My Key", "--json"], {
from: "user",
});

expect(logSpy).toHaveBeenCalledWith(JSON.stringify(response, null, 2));
});

it("prints error when key is missing from response", async () => {
vi.mocked(post).mockResolvedValue({});

await keysCommand.parseAsync(["create", "--name", "My Key"], {
from: "user",
});

expect(errorSpy).toHaveBeenCalledWith("Error: No key returned from API");
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("prints error when --name is missing", async () => {
await keysCommand.parseAsync(["create"], { from: "user" });

expect(errorSpy).toHaveBeenCalledWith(
"Error: --name is required",
);
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("prints error on API failure", async () => {
vi.mocked(post).mockRejectedValue(new Error("Unauthorized"));

await keysCommand.parseAsync(["create", "--name", "My Key"], {
from: "user",
});

expect(errorSpy).toHaveBeenCalledWith("Error: Unauthorized");
expect(exitSpy).toHaveBeenCalledWith(1);
});
});

describe("keys delete", () => {
it("deletes an API key by id and prints confirmation", async () => {
vi.mocked(del).mockResolvedValue({
status: "success",
message: "API key deleted successfully",
});

await keysCommand.parseAsync(["delete", "--id", "key-123"], {
from: "user",
});

expect(del).toHaveBeenCalledWith("/api/keys", { id: "key-123" });
expect(logSpy).toHaveBeenCalledWith("API key deleted successfully");
});

it("prints JSON with --json flag", async () => {
const response = { status: "success", message: "API key deleted successfully" };
vi.mocked(del).mockResolvedValue(response);

await keysCommand.parseAsync(["delete", "--id", "key-123", "--json"], {
from: "user",
});

expect(logSpy).toHaveBeenCalledWith(JSON.stringify(response, null, 2));
});

it("prints error when --id is missing", async () => {
await keysCommand.parseAsync(["delete"], { from: "user" });

expect(errorSpy).toHaveBeenCalledWith(
"Error: --id is required",
);
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("prints error on API failure", async () => {
vi.mocked(del).mockRejectedValue(new Error("API key not found"));

await keysCommand.parseAsync(["delete", "--id", "key-123"], {
from: "user",
});

expect(errorSpy).toHaveBeenCalledWith("Error: API key not found");
expect(exitSpy).toHaveBeenCalledWith(1);
});
});
4 changes: 4 additions & 0 deletions src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { notificationsCommand } from "./commands/notifications.js";
import { orgsCommand } from "./commands/orgs.js";
import { contentCommand } from "./commands/content.js";
import { tasksCommand } from "./commands/tasks.js";
import { accountsCommand } from "./commands/accounts.js";
import { keysCommand } from "./commands/keys.js";

const pkgPath = join(__dirname, "..", "package.json");
const { version } = JSON.parse(readFileSync(pkgPath, "utf-8"));
Expand All @@ -30,5 +32,7 @@ program.addCommand(sandboxesCommand);
program.addCommand(orgsCommand);
program.addCommand(tasksCommand);
program.addCommand(contentCommand);
program.addCommand(accountsCommand);
program.addCommand(keysCommand);

program.parse();
25 changes: 25 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,28 @@ export async function post(

return data;
}

export async function del(
path: string,
body: Record<string, unknown>,
): Promise<ApiResponse> {
const baseUrl = getBaseUrl();
const url = new URL(path, baseUrl);

const response = await fetch(url.toString(), {
method: "DELETE",
headers: {
"x-api-key": getApiKey(),
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});

const data: ApiResponse = await response.json();

if (!response.ok || data.status === "error") {
throw new Error(data.error || data.message || `Request failed: ${response.status}`);
}

return data;
}
47 changes: 47 additions & 0 deletions src/commands/accounts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Command } from "commander";
import { post } from "../client.js";
import { printJson, printError } from "../output.js";

const createCommand = new Command("create")
.description("Create a new account or retrieve an existing one by email or wallet")
.option("--email <email>", "Email address for the account")
.option("--wallet <wallet>", "Wallet address for the account")
.option("--json", "Output as JSON")
.action(async (opts) => {
if (!opts.email && !opts.wallet) {
printError("at least one of --email or --wallet is required");
return;
}

try {
const body: Record<string, unknown> = {};
if (opts.email) body.email = opts.email;
if (opts.wallet) body.wallet = opts.wallet;

const data = await post("/api/accounts", body);

if (opts.json) {
printJson(data);
} else {
const account = data.data as Record<string, unknown> | undefined;
if (!account || !account.account_id) {
printError("Account ID not found in API response");
return;
}
console.log(account.account_id);
}
} catch (err) {
printError((err as Error).message);
}
});

const upgradeCommand = new Command("upgrade")
.description("Upgrade your account to Pro")
.action(() => {
console.log("To upgrade to Pro, visit: https://chat.recoupable.com/settings");
});

export const accountsCommand = new Command("accounts")
.description("Manage your account")
.addCommand(createCommand)
.addCommand(upgradeCommand);
Loading
Loading