mirror of
https://github.com/openclaw/openclaw.git
synced 2026-06-03 23:24:07 +00:00
48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
export async function readBoundedResponseText(
|
|
response: Response,
|
|
label: string,
|
|
maxBytes: number,
|
|
): Promise<string> {
|
|
const contentLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
|
|
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
|
|
throw new Error(`${label} response body exceeded ${maxBytes} bytes.`);
|
|
}
|
|
|
|
if (!response.body) {
|
|
return "";
|
|
}
|
|
|
|
const reader = response.body.getReader();
|
|
const decoder = new TextDecoder();
|
|
const chunks: string[] = [];
|
|
let totalBytes = 0;
|
|
let canceled = false;
|
|
|
|
try {
|
|
for (;;) {
|
|
const { done, value } = await reader.read();
|
|
if (done) {
|
|
const tail = decoder.decode();
|
|
if (tail) {
|
|
chunks.push(tail);
|
|
}
|
|
break;
|
|
}
|
|
|
|
totalBytes += value.byteLength;
|
|
if (totalBytes > maxBytes) {
|
|
canceled = true;
|
|
await reader.cancel().catch(() => undefined);
|
|
throw new Error(`${label} response body exceeded ${maxBytes} bytes.`);
|
|
}
|
|
chunks.push(decoder.decode(value, { stream: true }));
|
|
}
|
|
} finally {
|
|
if (!canceled) {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
|
|
return chunks.join("");
|
|
}
|