338 lines
14 KiB
TypeScript
338 lines
14 KiB
TypeScript
import { describe, it, expect } from "vitest";
|
|
import { createHiveGridClient } from "./client.js";
|
|
|
|
// Local copies of the helpers used by client.test.ts — kept identical so the new
|
|
// suite stays independent of the existing test file (no shared-fixture edits).
|
|
function mockFetchSequence(responses: Array<Response | Error>): typeof fetch {
|
|
let index = 0;
|
|
return (async () => {
|
|
const next = responses[index++];
|
|
if (next === undefined) {
|
|
throw new Error("mock fetch exhausted");
|
|
}
|
|
if (next instanceof Error) throw next;
|
|
return next;
|
|
}) as unknown as typeof fetch;
|
|
}
|
|
|
|
function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}): Response {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { "content-type": "application/json", ...headers },
|
|
});
|
|
}
|
|
|
|
function textResponse(status: number, body: string, headers: Record<string, string> = {}): Response {
|
|
return new Response(body, { status, headers });
|
|
}
|
|
|
|
describe("createHiveGridClient — request body parsing", () => {
|
|
it("returns parsed text when the response is not JSON", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
fetch: mockFetchSequence([textResponse(200, "plain-pong", { "content-type": "text/plain" })]),
|
|
});
|
|
const result = await client.request<string>({ method: "GET", path: "/v1/ping" });
|
|
expect(result).toBe("plain-pong");
|
|
});
|
|
|
|
it("returns null for an empty non-JSON body", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
fetch: mockFetchSequence([textResponse(200, "")]),
|
|
});
|
|
const result = await client.request({ method: "GET", path: "/v1/empty" });
|
|
expect(result).toBeNull();
|
|
});
|
|
|
|
it("returns null when a JSON content-type carries an unparseable body", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
fetch: mockFetchSequence([textResponse(200, "{not-valid-json", { "content-type": "application/json" })]),
|
|
});
|
|
const result = await client.request({ method: "GET", path: "/v1/broken" });
|
|
expect(result).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("createHiveGridClient — idempotency edge cases", () => {
|
|
it("forwards a caller idempotency key on a non-mutating method", async () => {
|
|
const captured: { headers: Headers | null } = { headers: null };
|
|
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
|
|
captured.headers = init.headers as Headers;
|
|
return jsonResponse(200, {});
|
|
}) as unknown as typeof fetch;
|
|
|
|
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
|
await client.request({ method: "GET", path: "/v1/items", idempotencyKey: "explicit-get-key" });
|
|
// GET never auto-generates, but an explicit key must still be honored.
|
|
expect(captured.headers!.get("idempotency-key")).toBe("explicit-get-key");
|
|
});
|
|
});
|
|
|
|
describe("createHiveGridClient — URL building", () => {
|
|
it("allows an absolute path only when it stays on the configured origin", async () => {
|
|
const captured: { url: string | null } = { url: null };
|
|
const stub: typeof fetch = (async (url: string) => {
|
|
captured.url = url;
|
|
return jsonResponse(200, {});
|
|
}) as unknown as typeof fetch;
|
|
|
|
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
|
await client.request({ method: "GET", path: "https://api.example.com/v2/thing" });
|
|
expect(captured.url).toBe("https://api.example.com/v2/thing");
|
|
});
|
|
|
|
it.each(["https://other.example.test/v2/thing", "//other.example.test/v2/thing"])(
|
|
"fails closed for a cross-origin request path: %s",
|
|
async (path) => {
|
|
let calls = 0;
|
|
const stub: typeof fetch = (async () => {
|
|
calls += 1;
|
|
return jsonResponse(200, {});
|
|
}) as unknown as typeof fetch;
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
auth: { apiKey: "must-not-leak" },
|
|
tenantId: "tenant-must-not-leak",
|
|
fetch: stub,
|
|
});
|
|
|
|
await expect(client.request({ method: "GET", path })).rejects.toThrow(/cross-origin/);
|
|
expect(calls).toBe(0);
|
|
},
|
|
);
|
|
|
|
it("disables automatic redirects so custom credentials cannot cross origins", async () => {
|
|
const captured: { redirect: RequestRedirect | undefined; calls: number } = { redirect: undefined, calls: 0 };
|
|
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
|
|
captured.calls += 1;
|
|
captured.redirect = init.redirect;
|
|
return new Response(null, { status: 302, headers: { location: "https://other.example.test/collect" } });
|
|
}) as unknown as typeof fetch;
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
auth: { apiKey: "must-not-leak" },
|
|
retry: { maxAttempts: 1 },
|
|
fetch: stub,
|
|
});
|
|
|
|
await expect(client.request({ method: "GET", path: "/v1/redirect" })).rejects.toMatchObject({ status: 302 });
|
|
expect(captured.redirect).toBe("manual");
|
|
expect(captured.calls).toBe(1);
|
|
});
|
|
|
|
it("skips undefined query values while serializing the rest", async () => {
|
|
const captured: { url: string | null } = { url: null };
|
|
const stub: typeof fetch = (async (url: string) => {
|
|
captured.url = url;
|
|
return jsonResponse(200, {});
|
|
}) as unknown as typeof fetch;
|
|
|
|
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
|
await client.request({ method: "GET", path: "/v1/items", query: { a: 1, b: undefined, c: true } });
|
|
const parsed = new URL(captured.url!);
|
|
expect(parsed.searchParams.get("a")).toBe("1");
|
|
expect(parsed.searchParams.get("c")).toBe("true");
|
|
expect(parsed.searchParams.has("b")).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("createHiveGridClient — Retry-After handling", () => {
|
|
it("honors an HTTP-date Retry-After header, capped by maxDelayMs", async () => {
|
|
const future = new Date(Date.now() + 60_000).toUTCString();
|
|
const t0 = Date.now();
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
retry: { maxAttempts: 3, baseDelayMs: 1000, maxDelayMs: 5 },
|
|
fetch: mockFetchSequence([jsonResponse(429, { error: "rate" }, { "retry-after": future }), jsonResponse(200, { ok: true })]),
|
|
});
|
|
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
|
expect(result.ok).toBe(true);
|
|
// The 60s date must be clamped to the 5ms maxDelay, not waited out in full.
|
|
expect(Date.now() - t0).toBeLessThan(1000);
|
|
});
|
|
|
|
it("falls back to exponential backoff when Retry-After is unparseable", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
|
|
fetch: mockFetchSequence([jsonResponse(503, { error: "down" }, { "retry-after": "soon-ish" }), jsonResponse(200, { ok: true })]),
|
|
});
|
|
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
|
expect(result.ok).toBe(true);
|
|
});
|
|
|
|
it("treats a past HTTP-date Retry-After as a zero delay", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
retry: { maxAttempts: 2, baseDelayMs: 1000, maxDelayMs: 1000 },
|
|
fetch: mockFetchSequence([
|
|
jsonResponse(429, { error: "rate" }, { "retry-after": "Thu, 01 Jan 1970 00:00:00 GMT" }),
|
|
jsonResponse(200, { ok: true }),
|
|
]),
|
|
});
|
|
const t0 = Date.now();
|
|
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
|
expect(result.ok).toBe(true);
|
|
expect(Date.now() - t0).toBeLessThan(500);
|
|
});
|
|
});
|
|
|
|
describe("createHiveGridClient — network retry recovery", () => {
|
|
it("retries a transient network error and then succeeds", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
|
|
fetch: mockFetchSequence([new Error("ECONNRESET"), jsonResponse(200, { ok: true })]),
|
|
});
|
|
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
|
expect(result.ok).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("createHiveGridClient — error message extraction", () => {
|
|
it("falls back to `HTTP <status>` when the error body has no message", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
retry: { maxAttempts: 1 },
|
|
fetch: mockFetchSequence([jsonResponse(400, { error: {} })]),
|
|
});
|
|
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
|
|
name: "HiveGridApiError",
|
|
status: 400,
|
|
message: "HTTP 400",
|
|
});
|
|
});
|
|
|
|
it("falls back to `HTTP <status>` when `error` is not an object", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
retry: { maxAttempts: 1 },
|
|
fetch: mockFetchSequence([jsonResponse(422, { error: "validation failed" })]),
|
|
});
|
|
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
|
|
status: 422,
|
|
message: "HTTP 422",
|
|
});
|
|
});
|
|
|
|
it("uses `HTTP <status>` for a non-JSON error body and omits a missing requestId", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
retry: { maxAttempts: 1 },
|
|
fetch: mockFetchSequence([textResponse(500, "internal boom", { "content-type": "text/plain" })]),
|
|
});
|
|
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
|
|
status: 500,
|
|
message: "HTTP 500",
|
|
body: "internal boom",
|
|
requestId: undefined,
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("createHiveGridClient — pagination edge cases", () => {
|
|
it("follows nextPageToken cursors", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
fetch: mockFetchSequence([
|
|
jsonResponse(200, { data: [{ id: "a" }], nextPageToken: "tok-2" }),
|
|
jsonResponse(200, { data: [{ id: "b" }], nextPageToken: null }),
|
|
]),
|
|
});
|
|
const ids: string[] = [];
|
|
for await (const item of client.paginate<{ id: string }>("/v1/items")) {
|
|
ids.push(item.id);
|
|
}
|
|
expect(ids).toEqual(["a", "b"]);
|
|
});
|
|
|
|
it("stops cleanly when a page returns a null body", async () => {
|
|
let calls = 0;
|
|
const stub: typeof fetch = (async () => {
|
|
calls += 1;
|
|
// JSON literal null → readBody returns null → request resolves null.
|
|
return textResponse(200, "null", { "content-type": "application/json" });
|
|
}) as unknown as typeof fetch;
|
|
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
|
|
|
const items: unknown[] = [];
|
|
for await (const item of client.paginate("/v1/items")) items.push(item);
|
|
expect(items).toEqual([]);
|
|
expect(calls).toBe(1);
|
|
});
|
|
|
|
it("yields nothing when `data` is not an array", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
fetch: mockFetchSequence([jsonResponse(200, { data: { not: "an-array" } })]),
|
|
});
|
|
const items: unknown[] = [];
|
|
for await (const item of client.paginate("/v1/items")) items.push(item);
|
|
expect(items).toEqual([]);
|
|
});
|
|
|
|
it("breaks on an empty page even when a next cursor is present (safety stop)", async () => {
|
|
let calls = 0;
|
|
const stub: typeof fetch = (async () => {
|
|
calls += 1;
|
|
// A server that keeps advertising a cursor but never returns rows must not loop forever.
|
|
return jsonResponse(200, { data: [], nextCursor: "always-more" });
|
|
}) as unknown as typeof fetch;
|
|
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
|
|
|
const items: unknown[] = [];
|
|
for await (const item of client.paginate("/v1/items")) items.push(item);
|
|
expect(items).toEqual([]);
|
|
expect(calls).toBe(1);
|
|
});
|
|
|
|
it("respects the maxPages safety cap", async () => {
|
|
let calls = 0;
|
|
const stub: typeof fetch = (async () => {
|
|
calls += 1;
|
|
return jsonResponse(200, { data: [{ id: calls }], nextCursor: `c-${calls}` });
|
|
}) as unknown as typeof fetch;
|
|
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
|
|
|
const items: Array<{ id: number }> = [];
|
|
for await (const item of client.paginate<{ id: number }>("/v1/items", { maxPages: 3 })) {
|
|
items.push(item);
|
|
}
|
|
expect(items).toHaveLength(3);
|
|
expect(calls).toBe(3);
|
|
});
|
|
});
|
|
|
|
describe("createHiveGridClient — refreshAuth", () => {
|
|
it("refreshes and caches the bearer token via the configured getter", async () => {
|
|
let issued = 0;
|
|
const captured: Array<string | null> = [];
|
|
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
|
|
captured.push((init.headers as Headers).get("authorization"));
|
|
return jsonResponse(200, {});
|
|
}) as unknown as typeof fetch;
|
|
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
auth: { getToken: async () => `jwt-${++issued}` },
|
|
fetch: stub,
|
|
});
|
|
await client.refreshAuth();
|
|
expect(issued).toBe(1);
|
|
// The getter is re-invoked per request, so the next call advances the counter.
|
|
await client.request({ method: "GET", path: "/v1/me" });
|
|
expect(captured).toEqual(["Bearer jwt-2"]);
|
|
});
|
|
|
|
it("is a no-op when no token getter is configured", async () => {
|
|
const client = createHiveGridClient({
|
|
baseUrl: "https://api.example.com",
|
|
auth: { apiKey: "ak_123" },
|
|
fetch: mockFetchSequence([]),
|
|
});
|
|
await expect(client.refreshAuth()).resolves.toBeUndefined();
|
|
});
|
|
});
|