body.ts
This file
Path
source/utils/body.ts
242 lines · 11.3 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
The walk stopped after 200 commits: lines older than 37fc250 point at it.
Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 1why, one step back1import type {Options} from '../types/options.js';Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 2–3why, one step back2import {responseTypes, usualFormBoundarySize} from '../core/constants.js';3import {ResponseSizeError} from '../errors/ResponseSizeError.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 4why, one step back4Improve body size estimationSindre Sorhusbefore adoption7565d94
line 5why, one step back5const encoder = new TextEncoder();Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 6why, one step back6const responseSizeErrors = new WeakMap<ReadableStream, () => ResponseSizeError | undefined>();Improve docsSindre Sorhusbefore adoption8778439
line 7why, one step back7// The `Response` constructor rejects a body for these statuses, but some browsers (for example, Chromium and WebKit) still expose a body stream on such responses, so they must not be wrapped. A runtime that exposes a non-empty body for one of them, such as WebKit for 205, is therefore left unlimited and without progress events.Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 8why, one step back8const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);Improve body size estimationSindre Sorhusbefore adoption7565d94
line 9why, one step back9RefactorSindre Sorhusbefore adoptiona5ed57b
lines 10–23why, one step back10/**11Cancels the body of a request or response that is no longer used, unless `keep` still reads the same stream.1213Fire-and-forget: cancellation failures from already-locked or already-consumed streams are ignored, and the cancellation is not awaited since a clone leaves extra tee branches that keep the cancel promise pending per the Streams spec.14*/15export const cancelBody = (value: Request | Response | undefined, keep?: Request | Response): void => {16 const body = value?.body;17 if (body && body !== keep?.body) {18 void body.cancel().catch(() => undefined);19 }20};2122const getContentLength = (headers: Headers): number => Math.max(0, Number(headers.get('content-length')) || 0);23TweaksSindre Sorhusbefore adoption3ded2aa
lines 24–27why, one step back24// A multipart body sends every line break in a field name or string value as CRLF, and escapes line breaks and quotes in a field name or filename.25const normalizeLineBreaks = (value: string): string => value.replaceAll(/\r\n|\r|\n/g, '\r\n');26const escapeFormDataName = (name: string): string => name.replaceAll('\n', '%0A').replaceAll('\r', '%0D').replaceAll('"', '%22');27Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 28why, one step back28// eslint-disable-next-line @typescript-eslint/no-restricted-typesAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 29–34why, one step back29export const getBodySize = (body?: BodyInit | null): number => {30 if (!body) {31 return 0;32 }3334 if (body instanceof FormData) {Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 35why, one step back35 // This is an approximation, as FormData size calculation is not straightforward. The boundary length is a stand-in for the runtime's own, and every other byte is counted so the estimate errs high (except in Bun, see `usualFormBoundarySize`): an estimate below the real size makes `percent` reach its ceiling part way through the upload.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 36–38why, one step back36 let size = 0;3738 for (const [key, value] of body) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 39–48why, one step back39 size += usualFormBoundarySize + 4; // `--<boundary>\r\n`40 size += encoder.encode(`Content-Disposition: form-data; name="${escapeFormDataName(normalizeLineBreaks(key))}"`).byteLength;4142 if (value instanceof Blob) {43 // Most runtimes turn an appended `Blob` into a `File` named `blob`, but Bun keeps a `Blob` with an `undefined` name and sends an empty filename.44 size += encoder.encode(`; filename="${escapeFormDataName((value as Partial<File>).name ?? '')}"`).byteLength;45 size += encoder.encode(`\r\nContent-Type: ${value.type || 'application/octet-stream'}`).byteLength;46 }4748 size += 4; // The CRLF that ends the headers, plus the blank line.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 49why, one step back49 size += typeof value === 'string'TweaksSindre Sorhusbefore adoption3ded2aa
line 50why, one step back50 ? encoder.encode(normalizeLineBreaks(value)).byteLengthAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 51why, one step back51 : value.size;TweaksSindre Sorhusbefore adoption3ded2aa
line 52why, one step back52 size += 2; // The CRLF that ends the part.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 53–54why, one step back53 }54TweaksSindre Sorhusbefore adoption3ded2aa
lines 55–56why, one step back55 // The closing `--<boundary>--\r\n`. An empty `FormData` still sends it, but reports `0`, the documented total for an empty transfer.56 return size === 0 ? 0 : size + usualFormBoundarySize + 6;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 57–62why, one step back57 }5859 if (body instanceof Blob) {60 return body.size;61 }62Improve body size estimationSindre Sorhusbefore adoption7565d94
line 63why, one step back63 if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 64–67why, one step back64 return body.byteLength;65 }6667 if (typeof body === 'string') {Improve body size estimationSindre Sorhusbefore adoption7565d94
line 68why, one step back68 return encoder.encode(body).byteLength;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 69–71why, one step back69 }7071 if (body instanceof URLSearchParams) {Improve body size estimationSindre Sorhusbefore adoption7565d94
line 72why, one step back72 return encoder.encode(body.toString()).byteLength;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 73–74why, one step back73 }74Improve body size estimationSindre Sorhusbefore adoption7565d94
line 75why, one step back75 return 0;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 76–81why, one step back76};7778const withProgress = (stream: ReadableStream<Uint8Array>, totalBytes: number, onProgress: Options['onDownloadProgress'] | Options['onUploadProgress']): ReadableStream<Uint8Array> => {79 let previousChunk: Uint8Array | undefined;80 let transferredBytes = 0;81Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 82why, one step back82 return stream.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 83–96why, one step back83 transform(currentChunk, controller) {84 controller.enqueue(currentChunk);8586 if (previousChunk) {87 transferredBytes += previousChunk.byteLength;8889 let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;90 // Avoid reporting 100% progress before the stream is actually finished (in case totalBytes is inaccurate)91 if (percent >= 1) {92 // Epsilon is used here to get as close as possible to 100% without reaching it.93 // If we were to use 0.99 here, percent could potentially go backwards.94 percent = 1 - Number.EPSILON;95 }96Skip a needless request rebuild, report an unknown total as zero, and fix two stale testsSindre Sorhusbefore adoptionfa0eac4
lines 97–98why, one step back97 // An unknown total stays `0`, matching the `percent` computed from the same estimate and the documented progress shape.98 const reportedTotalBytes = totalBytes === 0 ? 0 : Math.max(totalBytes, transferredBytes);Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 99why, one step back99 onProgress?.({percent, totalBytes: reportedTotalBytes, transferredBytes}, previousChunk);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 100–104why, one step back100 }101102 previousChunk = currentChunk;103 },104 flush() {Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
lines 105–106why, one step back105 const finalChunk = previousChunk ?? new Uint8Array();106 transferredBytes += finalChunk.byteLength;Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 107why, one step back107 onProgress?.({percent: 1, totalBytes: transferredBytes, transferredBytes}, finalChunk);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 108–111why, one step back108 },109 }));110};111Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 112why, one step back112const copyResponseMetadata = (response: Response, originalResponse: Response, getError = originalResponse.body ? responseSizeErrors.get(originalResponse.body) : undefined): Response => {Fix `onDownloadProgress` dropping response `url`, `redirected`, and `type`Sindre Sorhusbefore adoptione893f16
line 113why, one step back113 const nativeClone = response.clone.bind(response);Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 114–115why, one step back114 if (response.body && getError) {115 responseSizeErrors.set(response.body, getError);Fix `onDownloadProgress` dropping response `url`, `redirected`, and `type`Sindre Sorhusbefore adoptione893f16
line 116why, one step back116Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 117–138why, one step back117 // Chromium replaces stream errors with a generic TypeError in native body methods.118 // Restore the size error, including on clones and download-progress wrappers.119 for (const type of Object.keys(responseTypes) as Array<keyof typeof responseTypes>) {120 if (typeof response[type] !== 'function') {121 continue;122 }123124 const nativeMethod = response[type].bind(response);125 Object.defineProperty(response, type, {126 async value() {127 try {128 return await nativeMethod();129 } catch (error) {130 throw getError() ?? error;131 }132 },133 writable: true,134 configurable: true,135 });136 }137 }138Fix `onDownloadProgress` dropping response `url`, `redirected`, and `type`Sindre Sorhusbefore adoptione893f16
lines 139–143why, one step back139 Object.defineProperties(response, {140 // The `Response` constructor cannot set these, so copy them over from the original response.141 url: {value: originalResponse.url},142 redirected: {value: originalResponse.redirected},143 type: {value: originalResponse.type},Check the callbacks before the constructor uses them and reject an array `hooks`Sindre Sorhusbefore adoption16b5936
line 144why, one step back144 // The constructor also rebuilds the header list under the mutable "response" guard, so a network response that arrived immutable would silently become mutable. Reusing the original's headers keeps the guard; a clone shares that same object, which the spec would have copied, but copying it would drop the guard again.Honour a late abort, count a no-op `content-encoding`, and keep wrapped headers immutableSindre Sorhusbefore adoption3f0e330
line 145why, one step back145 headers: {value: originalResponse.headers},Fix `onDownloadProgress` dropping response `url`, `redirected`, and `type`Sindre Sorhusbefore adoptione893f16
lines 146–148why, one step back146 // Native `clone()` creates a new `Response`, which would drop them again.147 // Keep the shim replaceable like `Response.prototype.clone` for instrumentation and mocks.148 clone: {Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 149–150why, one step back149 value() {150 const clone = nativeClone();Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 151why, one step back151 // Cloning replaces the original body too, so retain the error accessor on both branches.Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 152–157why, one step back152 if (response.body && getError) {153 responseSizeErrors.set(response.body, getError);154 }155156 return copyResponseMetadata(clone, response);157 },Fix `onDownloadProgress` dropping response `url`, `redirected`, and `type`Sindre Sorhusbefore adoptione893f16
lines 158–165why, one step back158 writable: true,159 configurable: true,160 },161 });162163 return response;164};165Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
lines 166–175why, one step back166// The body of a response the two wrappers below can pipe through, or `undefined` when they must leave it alone. A body an `afterResponse` hook already read, or locked with a reader, would otherwise fail with "The ReadableStream is locked" instead of the native "Body is unusable" error that names the actual mistake. A null body status cannot be given a replacement body at all, and there is nothing left to report once the body is gone.167const wrappableBody = (response: Response): ReadableStream<Uint8Array> | undefined => {168 const {body} = response;169 if (!body || response.bodyUsed || body.locked || nullBodyStatuses.has(response.status)) {170 return undefined;171 }172173 return body;174};175Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 176why, one step back176export const limitResponseSize = (response: Response, request: Request, maxResponseSize: number): Response => {Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
lines 177–178why, one step back177 const originalBody = wrappableBody(response);178 if (!originalBody || maxResponseSize === Number.POSITIVE_INFINITY) {Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 179–183why, one step back179 return response;180 }181182 let transferredBytes = 0;183 let sizeError: ResponseSizeError | undefined;Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
lines 184–185why, one step back184 const getOriginalSizeError = responseSizeErrors.get(originalBody);185 const body = originalBody.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 186–199why, one step back186 transform(chunk, controller) {187 transferredBytes += chunk.byteLength;188 if (transferredBytes > maxResponseSize) {189 sizeError = new ResponseSizeError(request, maxResponseSize);190 throw sizeError;191 }192193 controller.enqueue(chunk);194 },195 }));196197 return copyResponseMetadata(new Response(body, response), response, () => sizeError ?? getOriginalSizeError?.());198};199Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 200why, one step back200export const streamResponse = (response: Response, onDownloadProgress: Options['onDownloadProgress']) => {Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
lines 201–203why, one step back201 // A response with no wrappable body is not streamed, so it reports no progress. That covers a null body status, and a `HEAD` response in runtimes that give it no body.202 const originalBody = wrappableBody(response);203 if (!originalBody) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 204–206why, one step back204 return response;205 }206Honour a late abort, count a no-op `content-encoding`, and keep wrapped headers immutableSindre Sorhusbefore adoption3f0e330
lines 207–209why, one step back207 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after decompression. Using it for a content-coded response would report a total below what actually arrives, so every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`. `identity` is a registered no-op coding (RFC 9110 §8.4.2), so it leaves the length valid.208 const contentEncoding = response.headers.get('content-encoding')?.toLowerCase();209 const isContentCoded = Boolean(contentEncoding) && contentEncoding !== 'identity';RefactorSindre Sorhusbefore adoptiona5ed57b
line 210why, one step back210 const totalBytes = isContentCoded ? 0 : getContentLength(response.headers);Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
line 211why, one step back211 const body = withProgress(originalBody, totalBytes, onDownloadProgress);Fix `onDownloadProgress` dropping response `url`, `redirected`, and `type`Sindre Sorhusbefore adoptione893f16
line 212why, one step back212Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 213why, one step back213 return copyResponseMetadata(new Response(body, response), response);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 214–215why, one step back214};215Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 216why, one step back216// eslint-disable-next-line @typescript-eslint/no-restricted-typesAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 217why, one step back217export const streamRequest = (request: Request, onUploadProgress: Options['onUploadProgress'], originalBody?: BodyInit | null) => {Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
lines 218–226why, one step back218 // A Request-like object from a hook is used as-is, because the `Request` constructor cannot copy it. It would stringify the object as a URL here, so progress reporting is skipped for it. A body a hook already read, or locked with a reader, is left alone for the same reason as a response body: the runtime's own error names the actual mistake, where piping it would fail with "The ReadableStream is locked".219 if (220 !request.body221 || request.bodyUsed222 || request.body.locked223 || request.keepalive224 || request.mode === 'no-cors'225 || !(request instanceof globalThis.Request)226 ) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 227–229why, one step back227 return request;228 }229Progress from a declared content-length, and a throwing callback is never retriedSindre Sorhusbefore adoption0b1f462
line 230why, one step back230 // Use original body for size calculation since request.body is already a stream. A `ReadableStream` measures 0, so fall back to a `content-length` the caller declared. Browsers drop that header from a request, so this only helps outside browsers.RefactorSindre Sorhusbefore adoptiona5ed57b
line 231why, one step back231 const totalBytes = getBodySize(originalBody ?? request.body) || getContentLength(request.headers);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 232–236why, one step back232233 return new Request(request, {234 // @ts-expect-error - Types are outdated.235 duplex: 'half',236 body: withProgress(request.body, totalBytes, onUploadProgress),Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c
lines 237–238why, one step back237 // Bun drops the content type derived from a `FormData` body when the body is replaced, unless the headers are passed explicitly.238 headers: request.headers,Preserve request referrer optionsSindre Sorhusbefore adoptionf87efe6
lines 239–240why, one step back239 referrer: request.referrer,240 referrerPolicy: request.referrerPolicy,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 241–242why, one step back241 });242};