// The published fetch pebble, through the library's normal consumer test path: // a literal QUERY keeps its JSON through a transient retry and an auth refresh, // and stays in csrfToken's default safe set (503, then 401, then success). import { expect, test } from "bun:test"; import { authRefresh, csrfToken, retryingFetch, type FetchLike } from "@pebble/pebble/fetch"; const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); test("the fetch policies preserve and replay a literal QUERY JSON request", async () => { const url = "https://cine.example/search"; const body = JSON.stringify({ q: "pebble", page: 2 }); const answers = [json({ error: "busy" }, 503), json({ error: "expired" }, 401), json({ results: ["pebble"] })]; const calls: { url: string; method?: string; body: unknown; contentType: string | null; csrf: string | null }[] = []; const base: FetchLike = async (input, init) => { const headers = new Headers(init?.headers); calls.push({ url: String(input), method: init?.method, body: init?.body, contentType: headers.get("content-type"), csrf: headers.get("x-csrf-token"), }); return answers.shift()!; }; const doc = document.implementation.createHTMLDocument(""); const meta = doc.createElement("meta"); meta.name = "csrf-token"; meta.content = "not-for-a-safe-query"; doc.head.appendChild(meta); let refreshed = 0; const giveUps: unknown[] = []; const query = csrfToken({ doc })( authRefresh({ bounced: response => response.status === 401, refresh: async () => { refreshed++; return true; }, onGiveUp: outcome => giveUps.push(outcome), })(retryingFetch({ base, attempts: 2, backoff: 0 })), ); const response = await query(url, { method: "QUERY", headers: { "content-type": "application/json" }, body, }); expect(response.status).toBe(200); expect(await response.json()).toEqual({ results: ["pebble"] }); expect(refreshed).toBe(1); expect(giveUps).toEqual([]); expect(calls).toEqual( Array.from({ length: 3 }, () => ({ url, method: "QUERY", body, contentType: "application/json", csrf: null, })), ); });