import { test, afterEach } from "node:test"; import assert from "node:assert/strict"; import { apiRequest, listProducts, getProduct, login, getPrincipal, healthCheck, ApiError, } from "../src/lib/api.ts"; const originalFetch = globalThis.fetch; const org = "d66c798a-f764-4b88-8d13-ace328ff1010"; afterEach(() => { globalThis.fetch = originalFetch; }); test("invalid organization cannot trigger catalog requests", async () => { globalThis.fetch = async () => { assert.fail("Must not send a request"); }; await assert.rejects(listProducts("../auth/me")); }); test("catalog search is encoded and uses the deployed list shape", async () => { globalThis.fetch = async (url) => { assert.equal( url, `/api/v1/storefront/${org}/products?limit=12&offset=12&search=rose+%26+oud`, ); return new Response( JSON.stringify([{ id: org, name: "Rose", slug: "rose" }]), ); }; assert.equal((await listProducts(org, "rose & oud", 12))[0].name, "Rose"); }); test("product variants retain exact decimal and currency strings", async () => { globalThis.fetch = async () => new Response( JSON.stringify({ id: org, name: "Rose", slug: "rose", description: "", variants: [ { id: org, name: "Small", sku: "ROSE", price: "123.45", currency: "INR", attributes: {}, }, ], groups: [], }), ); assert.equal((await getProduct(org, org)).variants[0].price, "123.45"); }); test("login uses strict body and me uses opaque bearer token", async () => { globalThis.fetch = async (url, options) => { assert.equal(url, "/api/v1/auth/login"); assert.deepEqual(JSON.parse(options?.body as string), { organizationId: org, email: "staff@example.com", password: "private", }); return new Response( JSON.stringify({ accessToken: "opaque", tokenType: "Bearer", expiresAt: "2026-10-12T00:00:00.000Z", }), ); }; const session = await login(org, "staff@example.com", "private"); globalThis.fetch = async (url, options) => { assert.equal( new Headers(options?.headers).get("Authorization"), "Bearer opaque", ); return new Response( JSON.stringify({ userId: org, organizationId: org, sessionId: org, permissions: ["products.read"], }), ); }; assert.deepEqual((await getPrincipal(session.accessToken)).permissions, [ "products.read", ]); }); test("logout accepts 204 and errors retain code and request reference", async () => { globalThis.fetch = async () => new Response(null, { status: 204 }); assert.equal(await apiRequest("/auth/logout", { method: "POST" }), null); globalThis.fetch = async () => new Response( JSON.stringify({ message: "Denied", code: "ACCESS_DENIED", requestId: "ref", }), { status: 403 }, ); await assert.rejects( apiRequest("/auth/me"), (e) => e instanceof ApiError && e.status === 403 && e.requestId === "ref" && e.code === "ACCESS_DENIED", ); }); test("network errors are sanitized and aborts stay cancellable", async () => { globalThis.fetch = async () => { throw new Error("internal host"); }; await assert.rejects( apiRequest("/health/live"), (e) => e instanceof ApiError && e.code === "NETWORK_ERROR" && !e.message.includes("internal"), ); globalThis.fetch = async () => { throw new DOMException("Aborted", "AbortError"); }; await assert.rejects( apiRequest("/health/live"), (e) => e instanceof Error && e.name === "AbortError", ); }); test("malformed catalog and unsuccessful readiness status are rejected", async () => { globalThis.fetch = async () => new Response(JSON.stringify({ products: [] })); await assert.rejects( listProducts(org), (e) => e instanceof ApiError && e.code === "INVALID_RESPONSE", ); globalThis.fetch = async () => new Response(JSON.stringify({ status: "failed" })); await assert.rejects(healthCheck("ready")); }); test("malformed diagnostic values cannot leak objects into UI rendering", async () => { globalThis.fetch = async () => new Response( JSON.stringify({ message: ["invalid"], code: { private: "details" }, requestId: { bad: true }, }), { status: 400, headers: { "x-request-id": "safe-ref" } }, ); await assert.rejects( apiRequest("/auth/login"), (error) => error instanceof ApiError && error.code === undefined && error.requestId === "safe-ref", ); });