Skip to content

Commit 3e56254

Browse files
Fix for atob not loading in React Native (Azure#12412)
For some reason React native always tries to load .browser for `atob` so as workaround we can put the polyfill in the browser file.
1 parent 490e97a commit 3e56254

File tree

2 files changed

+44
-45
lines changed

2 files changed

+44
-45
lines changed
Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,50 @@
11
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT license.
33

4+
let safeatob: any;
5+
6+
// base64 character set, plus padding character (=)
7+
const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
8+
// Regular expression to check formal correctness of base64 encoded strings
9+
const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
10+
411
if ("function" !== typeof atob) {
5-
throw new Error("Your browser environment is missing the global `atob` function");
12+
// atob implementation for React Native
13+
safeatob = (str: string) => {
14+
// atob can work with strings with whitespaces, even inside the encoded part,
15+
// but only \t, \n, \f, \r and ' ', which can be stripped.
16+
str = String(str).replace(/[\t\n\f\r ]+/g, "");
17+
if (!b64re.test(str)) {
18+
throw new TypeError(
19+
"Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."
20+
);
21+
}
22+
23+
// Adding the padding if missing, for simplicity
24+
str += "==".slice(2 - (str.length & 3));
25+
let bitmap;
26+
let result = "";
27+
let r1;
28+
let r2;
29+
let i = 0;
30+
for (; i < str.length; ) {
31+
bitmap =
32+
(b64.indexOf(str.charAt(i++)) << 18) |
33+
(b64.indexOf(str.charAt(i++)) << 12) |
34+
((r1 = b64.indexOf(str.charAt(i++))) << 6) |
35+
(r2 = b64.indexOf(str.charAt(i++)));
36+
37+
result +=
38+
r1 === 64
39+
? String.fromCharCode((bitmap >> 16) & 255)
40+
: r2 === 64
41+
? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255)
42+
: String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255);
43+
}
44+
return result;
45+
};
46+
} else {
47+
safeatob = atob;
648
}
749

8-
export default atob;
50+
export default safeatob;

sdk/cosmosdb/cosmos/src/utils/atob.native.ts

Lines changed: 0 additions & 43 deletions
This file was deleted.

0 commit comments

Comments
 (0)