diff --git a/lib/Base64.js b/lib/Base64.js new file mode 100644 index 0000000..ded8abe --- /dev/null +++ b/lib/Base64.js @@ -0,0 +1,53 @@ +// Inspired by: https://github.com/davidchambers/Base64.js/blob/master/base64.js + +const chars = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + +const Base64 = { + btoa: (input = '') => { + let str = input + let output = '' + + for ( + let block = 0, charCode, i = 0, map = chars; + str.charAt(i | 0) || ((map = '='), i % 1); + output += map.charAt(63 & (block >> (8 - (i % 1) * 8))) + ) { + charCode = str.charCodeAt((i += 3 / 4)) + + if (charCode > 0xff) { + throw new Error( + "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range." + ) + } + + block = (block << 8) | charCode + } + + return output + }, + + atob: (input = '') => { + let str = input.replace(/=+$/, '') + let output = '' + + if (str.length % 4 == 1) { + throw new Error( + "'atob' failed: The string to be decoded is not correctly encoded." + ) + } + for ( + let bc = 0, bs = 0, buffer, i = 0; + (buffer = str.charAt(i++)); + ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4) + ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) + : 0 + ) { + buffer = chars.indexOf(buffer) + } + + return output + }, +} + +export default Base64 diff --git a/lib/toBase64.js b/lib/toBase64.js index 86243d9..7a32b8d 100644 --- a/lib/toBase64.js +++ b/lib/toBase64.js @@ -1,8 +1,10 @@ -export default function b64EncodeUnicode(str) { +import Base64 from './Base64' + +function b64EncodeUnicode(str) { // first we use encodeURIComponent to get percent-encoded UTF-8, // then we convert the percent encodings into raw bytes which // can be fed into btoa. - return btoa( + return Base64.btoa( encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes( match, p1 @@ -11,3 +13,5 @@ export default function b64EncodeUnicode(str) { }) ) } + +export default b64EncodeUnicode diff --git a/package.json b/package.json index 044e739..e551280 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "conekta-react-native", - "version": "0.1.0", + "version": "0.1.1", "description": "React Native Conekta wrapper", "main": "index.js", "scripts": { @@ -23,7 +23,7 @@ "author": "nure", "license": "MIT", "dependencies": { - "react-native-uuid": "^1.4.9", - "buffer": "^5.2.0" + "buffer": "^5.2.0", + "react-native-uuid": "^1.4.9" } } diff --git a/yarn.lock b/yarn.lock index 8651d57..449ffb0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -13,6 +13,10 @@ buffer@^5.2.0: base64-js "^1.0.2" ieee754 "^1.1.4" +conekta.js@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/conekta.js/-/conekta.js-0.5.0.tgz#2010377cf52d7cd110c994b1451961b0a80ff9ed" + ieee754@^1.1.4: version "1.1.12" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.12.tgz#50bf24e5b9c8bb98af4964c941cdb0918da7b60b"