( stream: ReadableStream<Uint8Array> | null | undefined, options: ReadStreamWithLimitOptions )
| 91 | } |
| 92 | |
| 93 | export async function readStreamToBufferWithLimit( |
| 94 | stream: ReadableStream<Uint8Array> | null | undefined, |
| 95 | options: ReadStreamWithLimitOptions |
| 96 | ): Promise<Buffer> { |
| 97 | if (!stream) return Buffer.alloc(0) |
| 98 | |
| 99 | const reader = stream.getReader() |
| 100 | const chunks: Buffer[] = [] |
| 101 | let totalBytes = 0 |
| 102 | const abortFromSignal = () => { |
| 103 | void reader.cancel(options.signal?.reason).catch(() => {}) |
| 104 | } |
| 105 | |
| 106 | try { |
| 107 | if (options.signal?.aborted) { |
| 108 | await reader.cancel(options.signal.reason).catch(() => {}) |
| 109 | throw toError(options.signal.reason ?? new Error('Aborted')) |
| 110 | } |
| 111 | options.signal?.addEventListener('abort', abortFromSignal, { once: true }) |
| 112 | |
| 113 | while (true) { |
| 114 | if (options.signal?.aborted) { |
| 115 | await reader.cancel(options.signal.reason).catch(() => {}) |
| 116 | throw toError(options.signal.reason ?? new Error('Aborted')) |
| 117 | } |
| 118 | |
| 119 | const { done, value } = await reader.read() |
| 120 | if (options.signal?.aborted) { |
| 121 | throw toError(options.signal.reason ?? new Error('Aborted')) |
| 122 | } |
| 123 | if (done) break |
| 124 | if (!value) continue |
| 125 | |
| 126 | totalBytes += value.byteLength |
| 127 | if (totalBytes > options.maxBytes) { |
| 128 | await reader.cancel().catch(() => {}) |
| 129 | throw new PayloadSizeLimitError({ |
| 130 | label: options.label, |
| 131 | maxBytes: options.maxBytes, |
| 132 | observedBytes: totalBytes, |
| 133 | }) |
| 134 | } |
| 135 | |
| 136 | await options.onChunk?.(value, totalBytes) |
| 137 | chunks.push(Buffer.from(value)) |
| 138 | } |
| 139 | } finally { |
| 140 | options.signal?.removeEventListener('abort', abortFromSignal) |
| 141 | reader.releaseLock() |
| 142 | } |
| 143 | |
| 144 | return Buffer.concat(chunks, totalBytes) |
| 145 | } |
| 146 | |
| 147 | export async function readNodeStreamToBufferWithLimit( |
| 148 | stream: NodeJS.ReadableStream | null | undefined, |
no test coverage detected