Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 1 addition & 26 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,24 +288,6 @@ export abstract class APIClient {
return this.requestAPIList(Page, { method: 'get', path, ...opts });
}

private calculateContentLength(body: unknown): string | null {
if (typeof body === 'string') {
if (typeof Buffer !== 'undefined') {
return Buffer.byteLength(body, 'utf8').toString();
}

if (typeof TextEncoder !== 'undefined') {
const encoder = new TextEncoder();
const encoded = encoder.encode(body);
return encoded.length.toString();
}
} else if (ArrayBuffer.isView(body)) {
return body.byteLength.toString();
}

return null;
}

async buildRequest<Req>(
inputOptions: FinalRequestOptions<Req>,
{ retryCount = 0 }: { retryCount?: number } = {},
Expand All @@ -319,8 +301,6 @@ export abstract class APIClient {
: isMultipartBody(options.body) ? options.body.body
: options.body ? JSON.stringify(options.body, null, 2)
: null;
const contentLength = this.calculateContentLength(body);

const url = this.buildURL(path!, query, defaultBaseURL);
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
options.timeout = options.timeout ?? this.timeout;
Expand All @@ -342,7 +322,7 @@ export abstract class APIClient {
headers[this.idempotencyHeader] = inputOptions.idempotencyKey;
}

const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });
const reqHeaders = this.buildHeaders({ options, headers, retryCount });

const req: RequestInit = {
method,
Expand All @@ -360,18 +340,13 @@ export abstract class APIClient {
private buildHeaders({
options,
headers,
contentLength,
retryCount,
}: {
options: FinalRequestOptions;
headers: Record<string, string | null | undefined>;
contentLength: string | null | undefined;
retryCount: number;
}): Record<string, string> {
const reqHeaders: Record<string, string> = {};
if (contentLength) {
reqHeaders['content-length'] = contentLength;
}

const defaultHeaders = this.defaultHeaders(options);
applyHeadersMut(reqHeaders, defaultHeaders);
Expand Down
96 changes: 96 additions & 0 deletions tests/content-length.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import Browserbase from '@browserbasehq/sdk';
import type { Fetch } from '@browserbasehq/sdk/core';
import http from 'node:http';
import type { AddressInfo } from 'node:net';

type RequestCapture = {
body: string;
contentLength: string | undefined;
};

async function captureRequest(
options: { fetch?: Fetch; httpAgent?: http.Agent } = {},
): Promise<RequestCapture> {
let resolveCapture: (capture: RequestCapture) => void;
let rejectCapture: (error: Error) => void;
const captured = new Promise<RequestCapture>((resolve, reject) => {
resolveCapture = resolve;
rejectCapture = reject;
});

const server = http.createServer((request, response) => {
const chunks: string[] = [];

request.setEncoding('utf8');
request.on('data', (chunk: string) => chunks.push(chunk));
request.on('error', rejectCapture);
request.on('aborted', () => rejectCapture(new Error('request aborted before the body was received')));
request.on('end', () => {
const body = chunks.join('');
response.writeHead(200, { 'content-type': 'application/json' });
response.end('{}');
resolveCapture({ body, contentLength: request.headers['content-length'] });
});
});

await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});

const { port } = server.address() as AddressInfo;
const client = new Browserbase({
apiKey: 'My API Key',
baseURL: `http://127.0.0.1:${port}`,
maxRetries: 0,
...options,
});

try {
await client.post('/foo', { body: { value: 'café 🌍' } });
return await captured;
} finally {
server.closeAllConnections();
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
}

describe('Content-Length on the wire', () => {
const prettyBody = JSON.stringify({ value: 'café 🌍' }, null, 2);

test('native fetch calculates the byte length', async () => {
const request = await captureRequest();

expect(request.body).toBe(prettyBody);
expect(request.contentLength).toBe(String(Buffer.byteLength(prettyBody)));
});

test('node-fetch calculates the byte length when an HTTP agent is provided', async () => {
const httpAgent = new http.Agent({ keepAlive: false });

try {
const request = await captureRequest({ httpAgent });

expect(request.body).toBe(prettyBody);
expect(request.contentLength).toBe(String(Buffer.byteLength(prettyBody)));
} finally {
httpAgent.destroy();
}
});

test('fetch middleware can transform the body before the byte length is calculated', async () => {
const nativeFetch = (globalThis as unknown as { fetch: Fetch }).fetch;
const minifyingFetch: Fetch = async (url, init) => {
const body = typeof init?.body === 'string' ? JSON.stringify(JSON.parse(init.body)) : init?.body;
return nativeFetch(url, { ...init, body });
};

const request = await captureRequest({ fetch: minifyingFetch });
const minifiedBody = JSON.stringify(JSON.parse(prettyBody));

expect(request.body).toBe(minifiedBody);
expect(request.contentLength).toBe(String(Buffer.byteLength(minifiedBody)));
});
});
16 changes: 13 additions & 3 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,13 +237,23 @@ describe('request building', () => {
const client = new Browserbase({ apiKey: 'My API Key' });

describe('Content-Length', () => {
test('handles multi-byte characters', async () => {
test('lets fetch handle multi-byte characters', async () => {
const { req } = await client.buildRequest({ path: '/foo', method: 'post', body: { value: '—' } });
expect((req.headers as Record<string, string>)['content-length']).toEqual('20');
expect((req.headers as Record<string, string>)['content-length']).toBeUndefined();
});

test('handles standard characters', async () => {
test('lets fetch handle standard characters', async () => {
const { req } = await client.buildRequest({ path: '/foo', method: 'post', body: { value: 'hello' } });
expect((req.headers as Record<string, string>)['content-length']).toBeUndefined();
});

test('preserves a caller-provided value', async () => {
const { req } = await client.buildRequest({
path: '/foo',
method: 'post',
body: { value: 'hello' },
headers: { 'Content-Length': '22' },
});
expect((req.headers as Record<string, string>)['content-length']).toEqual('22');
});
});
Expand Down
Loading