| 28 | } |
| 29 | |
| 30 | async function readResponseBody( |
| 31 | response: Response, |
| 32 | maxBytes: number, |
| 33 | ): Promise<string> { |
| 34 | const contentLength = getHeader(response.headers, 'content-length') |
| 35 | if (contentLength && Number(contentLength) > maxBytes) { |
| 36 | throw new Error(`Response is too large (${contentLength} bytes)`) |
| 37 | } |
| 38 | |
| 39 | if (!response.body) { |
| 40 | const buffer = await response.arrayBuffer() |
| 41 | if (buffer.byteLength > maxBytes) { |
| 42 | throw new Error(`Response is too large (${buffer.byteLength} bytes)`) |
| 43 | } |
| 44 | return new TextDecoder().decode(buffer) |
| 45 | } |
| 46 | |
| 47 | const reader = response.body.getReader() |
| 48 | const chunks: Uint8Array[] = [] |
| 49 | let totalBytes = 0 |
| 50 | |
| 51 | while (true) { |
| 52 | const { done, value } = await reader.read() |
| 53 | if (done) break |
| 54 | if (!value) continue |
| 55 | |
| 56 | totalBytes += value.byteLength |
| 57 | if (totalBytes > maxBytes) { |
| 58 | await reader.cancel() |
| 59 | throw new Error(`Response exceeded ${maxBytes} bytes`) |
| 60 | } |
| 61 | chunks.push(value) |
| 62 | } |
| 63 | |
| 64 | const body = new Uint8Array(totalBytes) |
| 65 | let offset = 0 |
| 66 | for (const chunk of chunks) { |
| 67 | body.set(chunk, offset) |
| 68 | offset += chunk.byteLength |
| 69 | } |
| 70 | |
| 71 | return new TextDecoder().decode(body) |
| 72 | } |
| 73 | |
| 74 | function decodeHtmlEntities(text: string): string { |
| 75 | const namedEntities: Record<string, string> = { |