export const BILLING_RESPONSE_MAX_BYTES = 2 * 1024 * 1024; export async function readBillingJsonResponse(response: Response, maxBytes = BILLING_RESPONSE_MAX_BYTES): Promise { const contentLength = response.headers.get("content-length"); if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) { await response.body?.cancel().catch(() => undefined); throw new Error("Billing provider response exceeds the configured size limit."); } if (!response.body) { throw new Error("Billing provider returned an empty JSON response."); } const reader = response.body.getReader(); const chunks: Uint8Array[] = []; let totalBytes = 0; while (true) { const chunk = await reader.read(); if (chunk.done) break; totalBytes += chunk.value.byteLength; if (totalBytes > maxBytes) { await reader.cancel().catch(() => undefined); throw new Error("Billing provider response exceeds the configured size limit."); } chunks.push(chunk.value); } const bytes = new Uint8Array(totalBytes); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } return JSON.parse(new TextDecoder().decode(bytes)) as unknown; }