Skip to content

Chrome DevTools for coding agents

fix: save binary request bodies byte for byte (#3404)

Jae Birdsalle3eb901fcc1d
diff --git a/src/formatters/NetworkFormatter.ts b/src/formatters/NetworkFormatter.ts
index 3feeb63e..375b5335 100644
--- a/src/formatters/NetworkFormatter.ts
+++ b/src/formatters/NetworkFormatter.ts
@@ -113,9 +113,22 @@ export class NetworkFormatter {
'Unable to save the request body to a file: no saveFile callback was configured.',
);
}
- if (data) {
+ // postData() is UTF-8 decoded, so binary bodies lose bytes; content()
+ // returns the raw bytes.
+ let bytes: Uint8Array | undefined;
+ try {
+ bytes = await this.#request.content();
+ } catch {
+ // Fall back to the decoded string below.
+ }
+ const body = bytes?.length
+ ? bytes
+ : data
+ ? Buffer.from(data)
+ : undefined;
+ if (body) {
const result = await this.#options.saveFile(
- Buffer.from(data),
+ body,
this.#options.requestFilePath,
'.network-request',
);
diff --git a/tests/formatters/NetworkFormatter.test.ts b/tests/formatters/NetworkFormatter.test.ts
index 861b6eef..378ee0cd 100644
--- a/tests/formatters/NetworkFormatter.test.ts
+++ b/tests/formatters/NetworkFormatter.test.ts
@@ -288,6 +288,38 @@ describe('NetworkFormatter', () => {
assert.strictEqual(json.responseBody, undefined);
});
+ it('should save binary request bodies byte for byte', async () => {
+ const bytes = new Uint8Array([0, 159, 146, 150, 255, 10, 13]);
+ const request = {
+ method: () => 'POST',
+ url: () => 'http://example.com',
+ headers: () => ({}),
+ hasPostData: () => true,
+ postData: () => new TextDecoder().decode(bytes),
+ content: async () => bytes,
+ response: () => null,
+ failure: () => null,
+ redirectChain: () => [],
+ fetchPostData: async () => undefined,
+ } as unknown as HTTPRequest;
+
+ using tmpDir = createTempDir('network-formatter-test-');
+ const reqPath = join(tmpDir.path, 'binary_req');
+ let saved: Uint8Array | undefined;
+ await NetworkFormatter.from(request, {
+ fetchData: true,
+ requestFilePath: reqPath,
+ saveFile: async (data, filename) => {
+ saved = data;
+ return {filename};
+ },
+ redactNetworkHeaders: false,
+ });
+
+ assert.ok(saved);
+ assert.deepStrictEqual([...saved], [...bytes]);
+ });
+
it('should not truncate large bodies when saving to file', async () => {
const largeBody = 'a'.repeat(10005);
const request = {