( source: Request | Response, maxBytes: number, signal: AbortSignal )
| 1122 | } |
| 1123 | |
| 1124 | const readArrayBufferLimited = async ( |
| 1125 | source: Request | Response, |
| 1126 | maxBytes: number, |
| 1127 | signal: AbortSignal |
| 1128 | ): Promise<ArrayBuffer> => { |
| 1129 | const header = source.headers.get("content-length") |
| 1130 | const contentLength = header !== null && /^\d+$/.test(header) ? Number(header) : undefined |
| 1131 | if (contentLength !== undefined && contentLength > maxBytes) { |
| 1132 | throw new BodyTooLargeError(maxBytes) |
| 1133 | } |
| 1134 | if (source.body === null) { |
| 1135 | return new ArrayBuffer(0) |
| 1136 | } |
| 1137 | // A constructed request can understate its content-length, so bytes are |
| 1138 | // counted on every runtime. Cancellation is not awaited, as the source's |
| 1139 | // cleanup may never settle. |
| 1140 | const limit = contentLength ?? maxBytes |
| 1141 | const reader = source.body.getReader() |
| 1142 | const cancel = () => { |
| 1143 | reader.cancel().catch(() => {}) |
| 1144 | } |
| 1145 | signal.addEventListener("abort", cancel, { once: true }) |
| 1146 | const chunks: Array<Uint8Array> = [] |
| 1147 | let bytes = 0 |
| 1148 | try { |
| 1149 | while (true) { |
| 1150 | const { done, value } = await reader.read() |
| 1151 | if (done) break |
| 1152 | bytes += value.byteLength |
| 1153 | if (bytes > limit) { |
| 1154 | cancel() |
| 1155 | throw bytes > maxBytes |
| 1156 | ? new BodyTooLargeError(maxBytes) |
| 1157 | : new Error(`Request body is longer than its content-length of ${contentLength}`) |
| 1158 | } |
| 1159 | chunks.push(value) |
| 1160 | } |
| 1161 | } finally { |
| 1162 | signal.removeEventListener("abort", cancel) |
| 1163 | reader.releaseLock() |
| 1164 | } |
| 1165 | const buffer = new Uint8Array(bytes) |
| 1166 | let offset = 0 |
| 1167 | for (const chunk of chunks) { |
| 1168 | buffer.set(chunk, offset) |
| 1169 | offset += chunk.byteLength |
| 1170 | } |
| 1171 | return buffer.buffer |
| 1172 | } |
| 1173 | |
| 1174 | /** |
| 1175 | * Attempts to construct an absolute `URL` for a server request safely. |
no test coverage detected