Improve body size estimation
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Reuse a single TextEncoder instance instead of creating new ones per call - Use `ArrayBuffer.isView()` to properly handle TypedArrays - Use `.byteLength` consistently on encode results - Remove unreachable code paths for non-BodyInit types Closes #734
authored by Sindre Sorhus · committed by Sindre Sorhus · parent bb8412e · Browse files · 3 files·+135 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+135 added−21 removed
- tests:+125 added−0 removed
- other:+10 added−21 removed
Provenance
- Commit
7565d94- Tree
e204754- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
bb8412e
3 files changed+135 added−21 removed
modified:source/core/constants.ts+2 added-2 removed
55 unmodified lines56 57 // The maximum value of a 32bit int (see issue #117)58 export const maxSafeTimeout = 2_147_483_647;59 60-// Size in bytes of a typical form boundary, used to help estimate upload size61-export const usualFormBoundarySize = new TextEncoder().encode('------WebKitFormBoundaryaxpyiPgbbPti10Rw').length;60+// Size in bytes of a typical form boundary (e.g. '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size61+export const usualFormBoundarySize = 40;62 63 /**64 Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.65 */223 unmodified linesmodified:source/utils/body.ts+8 added-19 removed
1234567894 unmodified lines141516171618191820212223242 unmodified lines272829302931323334353436373839384041424142434445464748495043515253544445464774 unmodified linesimport type {Options} from '../types/options.js';import {usualFormBoundarySize} from '../core/constants.js';
const encoder = new TextEncoder();
// eslint-disable-next-line @typescript-eslint/no-restricted-typesexport const getBodySize = (body?: BodyInit | null): number => { if (!body) { return 0;4 unmodified lines let size = 0;
for (const [key, value] of body) { size += usualFormBoundarySize; size += new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"`).length; size += encoder.encode(`Content-Disposition: form-data; name="${key}"`).byteLength; size += typeof value === 'string' ? new TextEncoder().encode(value).length ? encoder.encode(value).byteLength : value.size; }
return size;2 unmodified lines if (body instanceof Blob) { return body.size; }
if (body instanceof ArrayBuffer) { if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) { return body.byteLength; }
if (typeof body === 'string') { return new TextEncoder().encode(body).length; return encoder.encode(body).byteLength; }
if (body instanceof URLSearchParams) { return new TextEncoder().encode(body.toString()).length; return encoder.encode(body.toString()).byteLength; }
if ('byteLength' in body) { return (body).byteLength; }
if (typeof body === 'object' && body !== null) { try { const jsonString = JSON.stringify(body); return new TextEncoder().encode(jsonString).length; } catch { return 0; return 0; } }
return 0; // Default case, unable to determine size};
const withProgress = (stream: ReadableStream<Uint8Array>, totalBytes: number, onProgress: Options['onDownloadProgress'] | Options['onUploadProgress']): ReadableStream<Uint8Array> => { let previousChunk: Uint8Array | undefined;74 unmodified linesadded:test/body-size.ts+125 added
1+import test from 'ava';2+import {getBodySize} from '../source/utils/body.js';3+4+test('returns 0 for undefined', t => {5+ t.is(getBodySize(undefined), 0);6+});7+8+test('returns 0 for null', t => {9+ t.is(getBodySize(null), 0);10+});11+12+test('returns correct size for ASCII string', t => {13+ t.is(getBodySize('hello'), 5);14+});15+16+test('returns correct size for multi-byte string', t => {17+ // Emoji is 4 bytes in UTF-818+ t.is(getBodySize('😀'), 4);19+ t.is(getBodySize('hello 😀 world'), 16);20+});21+22+test('returns correct size for empty string', t => {23+ t.is(getBodySize(''), 0);24+});25+26+test('returns correct size for ArrayBuffer', t => {27+ const buffer = new ArrayBuffer(16);28+ t.is(getBodySize(buffer), 16);29+});30+31+test('returns correct size for Uint8Array', t => {32+ const array = new Uint8Array([1, 2, 3, 4, 5]);33+ t.is(getBodySize(array), 5);34+});35+36+test('returns correct size for Uint16Array', t => {37+ const array = new Uint16Array([1, 2, 3]);38+ t.is(getBodySize(array), 6); // 3 elements × 2 bytes39+});40+41+test('returns correct size for Float64Array', t => {42+ const array = new Float64Array([1, 2]);43+ t.is(getBodySize(array), 16); // 2 elements × 8 bytes44+});45+46+test('returns correct size for DataView', t => {47+ const buffer = new ArrayBuffer(10);48+ const view = new DataView(buffer);49+ t.is(getBodySize(view), 10);50+});51+52+test('returns correct size for TypedArray subarray', t => {53+ const full = new Uint8Array([1, 2, 3, 4, 5]);54+ const sub = full.subarray(1, 3);55+ // Should return the view's byteLength (2), not the underlying buffer's (5)56+ t.is(getBodySize(sub), 2);57+});58+59+test('returns 0 for zero-length ArrayBuffer', t => {60+ t.is(getBodySize(new ArrayBuffer(0)), 0);61+});62+63+test('returns correct size for Blob', t => {64+ const blob = new Blob(['hello world']);65+ t.is(getBodySize(blob), 11);66+});67+68+test('returns correct size for Blob with multi-byte content', t => {69+ const blob = new Blob(['😀']);70+ t.is(getBodySize(blob), 4);71+});72+73+test('returns correct size for File', t => {74+ const file = new File(['hello world'], 'test.txt', {type: 'text/plain'});75+ t.is(getBodySize(file), 11);76+});77+78+test('returns correct size for URLSearchParams', t => {79+ const parameters = new URLSearchParams({foo: 'bar', baz: 'qux'});80+ t.is(getBodySize(parameters), 15); // 'foo=bar&baz=qux'81+});82+83+test('returns correct size for empty URLSearchParams', t => {84+ const parameters = new URLSearchParams();85+ t.is(getBodySize(parameters), 0);86+});87+88+test('returns 0 for ReadableStream', t => {89+ const stream = new ReadableStream();90+ t.is(getBodySize(stream), 0);91+});92+93+test('returns 0 for empty FormData', t => {94+ const formData = new FormData();95+ t.is(getBodySize(formData), 0);96+});97+98+test('FormData returns a positive size', t => {99+ const formData = new FormData();100+ formData.append('key', 'value');101+ const size = getBodySize(formData);102+ t.true(size > 0, `Expected positive size, got ${size}`);103+});104+105+test('FormData size increases with more fields', t => {106+ const formData1 = new FormData();107+ formData1.append('a', '1');108+ const size1 = getBodySize(formData1);109+110+ const formData2 = new FormData();111+ formData2.append('a', '1');112+ formData2.append('b', '2');113+ const size2 = getBodySize(formData2);114+115+ t.true(size2 > size1, `Two fields (${size2}) should be larger than one field (${size1})`);116+});117+118+test('FormData with Blob value accounts for blob size', t => {119+ const formData = new FormData();120+ formData.append('file', new Blob(['hello world']));121+122+ const size = getBodySize(formData);123+ // Size should be at least the blob content size (11 bytes)124+ t.true(size >= 11, `Expected size >= 11, got ${size}`);125+});