-
Notifications
You must be signed in to change notification settings - Fork 89
/
base64.ts
68 lines (56 loc) · 1.5 KB
/
base64.ts
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
import nacl from 'tweetnacl-util';
function encodeUint8Array(value: Uint8Array, urlSafe: boolean): string {
const encoded = nacl.encodeBase64(value);
if (!urlSafe) {
return encoded;
}
return encodeURIComponent(encoded);
}
function decodeToUint8Array(value: string, urlSafe: boolean): Uint8Array {
if (urlSafe) {
value = decodeURIComponent(value);
}
return nacl.decodeBase64(value);
}
function encode(value: string | object | Uint8Array, urlSafe = false): string {
let uint8Array: Uint8Array;
if (value instanceof Uint8Array) {
uint8Array = value;
} else {
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
uint8Array = nacl.decodeUTF8(value);
}
return encodeUint8Array(uint8Array, urlSafe);
}
function decode(
value: string,
urlSafe = false
): {
toString(): string;
toObject<T>(): T | null;
toUint8Array(): Uint8Array;
} {
const decodedUint8Array = decodeToUint8Array(value, urlSafe);
return {
toString(): string {
return nacl.encodeUTF8(decodedUint8Array);
},
toObject<T>(): T | null {
try {
return JSON.parse(nacl.encodeUTF8(decodedUint8Array)) as T;
} catch (e) {
return null;
}
},
toUint8Array(): Uint8Array {
return decodedUint8Array;
}
};
}
export const Base64 = {
encode,
decode
};
export type { encode, decode };