import { describe, expect, it } from "vitest"; import { RestApiValidationError } from "../../errors.js"; import { decodeWorkerBinaryResponse } from "./decode-worker-binary-response.js"; describe("decodeWorkerBinaryResponse", () => { it("copies a Uint8Array into a plain Uint8Array with the same bytes", () => { const source = new Uint8Array([1, 2, 255]); const result = decodeWorkerBinaryResponse(source); expect(result).toBeInstanceOf(Uint8Array); expect(result.constructor).toBe(Uint8Array); expect(Array.from(result)).toEqual([1, 2, 255]); source[0] = 9; expect(result[0]).toBe(1); }); it("converts worker Buffer JSON into a plain Uint8Array", () => { const result = decodeWorkerBinaryResponse({ type: "Buffer", data: [37, 80, 68, 70], }); expect(result.constructor).toBe(Uint8Array); expect(Array.from(result)).toEqual([37, 80, 68, 70]); }); it("converts empty Buffer JSON into a zero-length Uint8Array", () => { const result = decodeWorkerBinaryResponse({ type: "Buffer", data: [] }); expect(result).toBeInstanceOf(Uint8Array); expect(result.byteLength).toBe(0); }); it("rejects a missing discriminant", () => { expect(() => decodeWorkerBinaryResponse({ data: [1] })).toThrow( RestApiValidationError, ); }); it("rejects a non-Buffer discriminant", () => { expect(() => decodeWorkerBinaryResponse({ type: "Array", data: [1] }), ).toThrow(RestApiValidationError); }); it("rejects a non-array data field", () => { expect(() => decodeWorkerBinaryResponse({ type: "Buffer", data: "00ff" }), ).toThrow(RestApiValidationError); }); it("rejects a byte outside 0 through 255", () => { expect(() => decodeWorkerBinaryResponse({ type: "Buffer", data: [256] }), ).toThrow(RestApiValidationError); }); it("rejects a negative byte", () => { expect(() => decodeWorkerBinaryResponse({ type: "Buffer", data: [-1] }), ).toThrow(RestApiValidationError); }); it("reports the index of a non-integer byte", () => { try { decodeWorkerBinaryResponse({ type: "Buffer", data: [1, 1.5] }); } catch (error) { expect(error).toBeInstanceOf(RestApiValidationError); if (!(error instanceof RestApiValidationError)) { throw error; } expect(error.details.zodError.issues).toEqual([ expect.objectContaining({ path: ["data", 1] }), ]); return; } throw new Error("Expected binary response validation to fail"); }); it("redacts malformed binary data from validation errors", () => { const data = Array.from({ length: 4096 }, () => 0); data[4095] = 256; try { decodeWorkerBinaryResponse({ type: "Buffer", data }); } catch (error) { expect(error).toBeInstanceOf(RestApiValidationError); if (!(error instanceof RestApiValidationError)) { throw error; } expect(error.details.data).toEqual({ dataType: "binary", redacted: true, }); return; } throw new Error("Expected malformed binary response to fail"); }); it("rejects a string payload", () => { expect(() => decodeWorkerBinaryResponse("not-binary")).toThrow( RestApiValidationError, ); }); });