import { z } from "zod"; import { REDACTED_BINARY_RESPONSE_DATA, RestApiValidationError, } from "../../errors.js"; export { REDACTED_BINARY_RESPONSE_DATA }; const workerBinaryResponseSchema = z.union([ z.instanceof(Uint8Array).transform((value) => new Uint8Array(value)), z .object({ data: z.unknown(), type: z.literal("Buffer"), }) .transform((value, context) => { if (!Array.isArray(value.data)) { context.addIssue({ code: z.ZodIssueCode.custom, message: "data must be an array of bytes", path: ["data"], }); return z.NEVER; } const bytes = new Uint8Array(value.data.length); for (let index = 0; index < value.data.length; index += 1) { const item = value.data[index]; if ( typeof item !== "number" || !Number.isInteger(item) || item < 0 || item > 255 ) { context.addIssue({ code: z.ZodIssueCode.custom, message: "byte must be an integer from 0 through 255", path: ["data", index], }); return z.NEVER; } bytes[index] = item; } return bytes; }), ]); export function decodeWorkerBinaryResponse(value: unknown): Uint8Array { const result = workerBinaryResponseSchema.safeParse(value); if (!result.success) { throw new RestApiValidationError( `Binary response is malformed: ${result.error.message}`, { data: REDACTED_BINARY_RESPONSE_DATA, zodError: result.error, }, ); } return result.data; }