|
1 | 1 | // Copyright (c) Microsoft Corporation. |
2 | 2 | // Licensed under the MIT license. |
3 | 3 |
|
| 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 | + |
4 | 11 | 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; |
6 | 48 | } |
7 | 49 |
|
8 | | -export default atob; |
| 50 | +export default safeatob; |
0 commit comments