From b370b7ac6cd9e09c49d969cbf5af5549d77f2871 Mon Sep 17 00:00:00 2001 From: George Fu Date: Tue, 12 Mar 2024 17:22:37 +0000 Subject: [PATCH] fix(util-base64): allow arrays to stand in for Uint8Array (runtime only) --- .changeset/old-kangaroos-rhyme.md | 5 +++++ packages/util-base64/src/toBase64.browser.spec.ts | 8 ++++++++ packages/util-base64/src/toBase64.browser.ts | 10 +++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 .changeset/old-kangaroos-rhyme.md diff --git a/.changeset/old-kangaroos-rhyme.md b/.changeset/old-kangaroos-rhyme.md new file mode 100644 index 00000000000..9d08bcd9ac0 --- /dev/null +++ b/.changeset/old-kangaroos-rhyme.md @@ -0,0 +1,5 @@ +--- +"@smithy/util-base64": patch +--- + +allow arrays to stand in for Uint8Array in toBase64 diff --git a/packages/util-base64/src/toBase64.browser.spec.ts b/packages/util-base64/src/toBase64.browser.spec.ts index 81261f095ef..2be1ecc4fd2 100644 --- a/packages/util-base64/src/toBase64.browser.spec.ts +++ b/packages/util-base64/src/toBase64.browser.spec.ts @@ -4,6 +4,7 @@ import type { Encoder } from "@smithy/types"; import testCases from "./__mocks__/testCases.json"; +import { fromBase64 } from "./fromBase64.browser"; import { toBase64 } from "./toBase64.browser"; describe(toBase64.name, () => { @@ -19,4 +20,11 @@ describe(toBase64.name, () => { expect(() => (toBase64 as Encoder)(new Date())).toThrow(); expect(() => (toBase64 as Encoder)({})).toThrow(); }); + + it("allows array to stand in for Uint8Array", () => { + expect(() => (toBase64 as Encoder)([])).not.toThrow(); + + const helloUtf8Array = fromBase64("aGVsbG8="); + expect(toBase64(([...helloUtf8Array] as unknown) as Uint8Array)).toEqual("aGVsbG8="); + }); }); diff --git a/packages/util-base64/src/toBase64.browser.ts b/packages/util-base64/src/toBase64.browser.ts index bdfad0f9b15..f58e4eb32f3 100644 --- a/packages/util-base64/src/toBase64.browser.ts +++ b/packages/util-base64/src/toBase64.browser.ts @@ -17,9 +17,17 @@ export function toBase64(_input: Uint8Array | string): string { } else { input = _input as Uint8Array; } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + + const isArrayLike = typeof input === "object" && typeof input.length === "number"; + const isUint8Array = + typeof input === "object" && + typeof (input as Uint8Array).byteOffset === "number" && + typeof (input as Uint8Array).byteLength === "number"; + + if (!isArrayLike && !isUint8Array) { throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); } + let str = ""; for (let i = 0; i < input.length; i += 3) { let bits = 0;