Skip to content

Commit

Permalink
correctly read string length
Browse files Browse the repository at this point in the history
  • Loading branch information
MustafaHaddara committed Aug 19, 2024
1 parent 91637aa commit 08ab734
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/opentelemetry-sdk-trace-web/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ export function getFetchBodyLength(...args: Parameters<typeof fetch>) {
return info
.clone()
.text()
.then(t => t.length);
.then(t => getByteLength(t));
}
}

Expand Down Expand Up @@ -247,21 +247,26 @@ export function getXHRBodyLength(
if (body instanceof FormData) {
// typescript doesn't like it when we pass FormData into URLSearchParams
// even though this is actually totally valid
return new URLSearchParams(body as any).toString().length;
return getByteLength(new URLSearchParams(body as any).toString());
}

if (body instanceof URLSearchParams) {
return body.toString().length;
return getByteLength(body.toString());
}

if (typeof body === 'string') {
return body.length;
return getByteLength(body);
}

DIAG_LOGGER.warn('unknown body type');
return 0;
}

const TEXT_ENCODER = new TextEncoder();
function getByteLength(s: string): number {
return TEXT_ENCODER.encode(s).byteLength;
}

/**
* sort resources by startTime
* @param filteredResources
Expand Down
3 changes: 3 additions & 0 deletions packages/opentelemetry-sdk-trace-web/test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,9 @@ describe('utils', () => {
});
assert.strictEqual(getXHRBodyLength(jsonString), 36);
assert.strictEqual(getXHRBodyLength('hello world'), 11);
assert.strictEqual(getXHRBodyLength('π'), 2); // one character, 2 bytes
assert.strictEqual(getXHRBodyLength('🔥🔪😭'), 12); // each emoji is 4 bytes
assert.strictEqual(getXHRBodyLength('مرحبا بالعالم'), 25); // hello world in Arabic is 25 bytes
assert.strictEqual(getXHRBodyLength(''), 0);
});
});
Expand Down

0 comments on commit 08ab734

Please sign in to comment.