Skip to content

Commit

Permalink
fix: test before using Buffers (#3400)
Browse files Browse the repository at this point in the history
  • Loading branch information
ST-DDT authored Feb 19, 2025
1 parent 6f1a0f8 commit ec7c9a8
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/internal/base64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* @example const encodedHeader = toBase64(JSON.stringify(header));
*/
export const toBase64: (input: string) => string =
typeof Buffer === 'undefined'
typeof Buffer === 'undefined' || !bufferFeatureCheck('base64')
? (input) => {
const utf8Bytes = new TextEncoder().encode(input);
const binaryString = Array.from(utf8Bytes, (byte) =>
Expand All @@ -39,10 +39,27 @@ export const toBase64: (input: string) => string =
* @example const encodedHeader = toBase64Url(JSON.stringify(header));
*/
export const toBase64Url: (input: string) => string =
typeof Buffer === 'undefined'
typeof Buffer === 'undefined' || !bufferFeatureCheck('base64url')
? (input) =>
toBase64(input)
.replaceAll('+', '-')
.replaceAll('/', '_')
.replaceAll(/=+$/g, '')
: (input) => Buffer.from(input).toString('base64url');

/**
* Checks whether the environment supports the given encoding on the `Buffer` class.
* This is required because some `Buffer` polyfills do not support all encodings.
*
* @param encoding The encoding to check.
*
* @see https://www.npmjs.com/package/buffer
* @see https://github.com/feross/buffer/issues/309
*/
function bufferFeatureCheck(encoding: BufferEncoding): boolean {
try {
return typeof Buffer.from('test').toString(encoding) === 'string';
} catch {
return false;
}
}

0 comments on commit ec7c9a8

Please sign in to comment.