-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
71 lines (55 loc) · 1.93 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const runningOnBrowser = typeof window !== 'undefined'
const base64urlToBase64 = base64UrlString => {
// Replace non-url compatible chars with base64 standard chars
const base64 = base64UrlString
.replace(/-/g, '+')
.replace(/_/g, '/')
// Pad out with standard base64 required padding characters if missing
const missingPadding = '='.repeat((4 - base64.length % 4) % 4)
return base64 + missingPadding
}
const base64Decode = data => {
if (runningOnBrowser) {
return atob(data)
}
// atob polyfill for Node
return Buffer.from(data, 'base64').toString('binary')
}
const base64Encode = data => {
if (runningOnBrowser) {
return btoa(data)
}
// btoa polyfill for Node
return Buffer.from(data).toString('base64')
}
const base64ToUint8Array = base64String => {
// base64 sanitizing
const base64 = base64urlToBase64(base64String)
// base64 decoding
const rawData = base64Decode(base64)
// Converting raw data to Uint8Array
return Uint8Array.from(rawData, char => char.charCodeAt(0))
}
const typedArrayToBase64 = typedArray => {
const string = typedArray.reduce((data, byte) => {
return data + String.fromCharCode(byte)
}, '')
return base64Encode(string)
}
const uint8ArrayToBase64 = typedArrayToBase64
const typedArrayToArrayBuffer = typedArray => {
return typedArray.buffer
}
const uint8ArrayToArrayBuffer = typedArrayToArrayBuffer
const arrayBufferToUint8Array = arrayBuffer => {
return new Uint8Array(arrayBuffer)
}
const base64ToArrayBuffer = base64String => {
const uint8Array = base64ToUint8Array(base64String)
return uint8ArrayToArrayBuffer(uint8Array)
}
const arrayBufferToBase64 = arrayBuffer => {
const uint8Array = arrayBufferToUint8Array(arrayBuffer)
return uint8ArrayToBase64(uint8Array)
}
export { base64ToUint8Array, uint8ArrayToBase64, uint8ArrayToArrayBuffer, arrayBufferToUint8Array, base64ToArrayBuffer, arrayBufferToBase64, typedArrayToArrayBuffer, typedArrayToBase64 }