Repository Public
1import { afterEach, describe, expect, it, vi } from "vitest";2import { apiGet, apiPost, transport } from "./client";3import { ApiError } from "./errors";45// Node's Request (unlike a browser's) cannot resolve the same-origin relative URLs the client uses: give it a base.6// Hoisted so it is in place before the client module captures `Request`.7vi.hoisted(() => {8 const Native = globalThis.Request;9 globalThis.Request = class extends Native {10 constructor(input: RequestInfo | URL, init?: RequestInit) {11 super(typeof input === "string" && input.startsWith("/") ? `http://localhost${input}` : input, init);12 }13 };14});1516const respond = (status: number, body: unknown, headers: Record<string, string> = {}) =>17 new Response(body === undefined ? null : JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } });1819describe("typed API client", () => {20 afterEach(() => {21 vi.unstubAllGlobals();22 transport.setCsrf(null);23 });2425 it("returns the typed body on success and serialises array parameters comma-separated", async () => {26 const fetchMock = vi.fn(async (_r: Request) => respond(200, { from: "a", to: "b", resolution: "raw", series: [], availability: {} }));27 vi.stubGlobal("fetch", fetchMock);28 const out = await apiGet("/nodes/{id}/metrics", { path: { id: "n1" }, query: { metrics: ["cpu.usage", "mem.used"] } });29 expect(out.series).toEqual([]);30 const url = new URL(fetchMock.mock.calls[0]?.[0].url ?? "");31 expect(url.pathname).toBe("/api/v1/nodes/n1/metrics");32 expect(url.searchParams.get("metrics")).toBe("cpu.usage,mem.used");33 });3435 it("maps an error envelope to ApiError with code, details, correlation id and Retry-After", async () => {36 vi.stubGlobal("fetch", vi.fn(async () => respond(403, { error: { code: "forbidden", message: "You do not have permission to do this.", correlation_id: "c-42", details: { permission: "audit.read" } } }, { "Retry-After": "7" })));37 const e = await apiGet("/audit").catch((x: unknown) => x);38 expect(e).toBeInstanceOf(ApiError);39 const err = e as ApiError;40 expect(err).toMatchObject({ status: 403, code: "forbidden", correlationId: "c-42", retryAfter: 7, forbidden: true, missingPermission: "audit.read" });41 expect(err.message).toBe("You do not have permission to do this.");42 });4344 it("recognises 501 (not implemented yet), 503 and conflicts by their code", async () => {45 const fetchMock = vi.fn()46 .mockResolvedValueOnce(respond(501, { error: { code: "not_implemented", message: "This operation is not available.", correlation_id: "c1" } }))47 .mockResolvedValueOnce(respond(503, { error: { code: "orchestrator_frozen", message: "frozen", correlation_id: "c2" } }))48 .mockResolvedValueOnce(respond(409, { error: { code: "handle_taken", message: "This handle is already in use.", correlation_id: "c3" } }));49 vi.stubGlobal("fetch", fetchMock);50 await expect(apiGet("/nodes")).rejects.toMatchObject({ notImplemented: true, code: "not_implemented" });51 await expect(apiGet("/nodes")).rejects.toMatchObject({ unavailable: true, code: "orchestrator_frozen" });52 await expect(apiPost("/invitations/transaction/profile", { body: { handle: "x", display_name: "X" } })).rejects.toMatchObject({ status: 409, code: "handle_taken", correlationId: "c3" });53 });5455 it("falls back to the HTTP status for non-JSON error bodies and to the header for the correlation id", async () => {56 vi.stubGlobal("fetch", vi.fn(async () => new Response("<html>Bad Gateway</html>", { status: 502, headers: { "Content-Type": "text/html", "X-Correlation-Id": "hdr-1" } })));57 await expect(apiGet("/nodes")).rejects.toMatchObject({ status: 502, code: "http_502", correlationId: "hdr-1", unavailable: true });58 });5960 it("reports network failures as status 0", async () => {61 vi.stubGlobal("fetch", vi.fn(async () => { throw new TypeError("Failed to fetch"); }));62 await expect(apiGet("/nodes")).rejects.toMatchObject({ status: 0, code: "network", network: true });63 });6465 it("sends the CSRF token and custom headers on mutations, and a JSON body", async () => {66 const fetchMock = vi.fn(async (_r: Request) => respond(201, { id: "a1" }));67 vi.stubGlobal("fetch", fetchMock);68 transport.setCsrf("csrf-1");69 await apiPost("/actions", { body: { type: "inventory.refresh", target: { kind: "node", id: "n1" }, override_maintenance: false }, headers: { "Idempotency-Key": "k-1" } });70 const req = fetchMock.mock.calls[0]?.[0] as Request;71 expect(req.method).toBe("POST");72 expect(req.headers.get("X-MCC-CSRF")).toBe("csrf-1");73 expect(req.headers.get("Idempotency-Key")).toBe("k-1");74 expect(await req.json()).toMatchObject({ type: "inventory.refresh" });75 });76});77