-
-
Notifications
You must be signed in to change notification settings - Fork 446
/
encode.ts
77 lines (66 loc) · 2.09 KB
/
encode.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
69
70
71
72
73
74
75
76
77
import { Buffer } from "https://deno.land/std@0.158.0/node/buffer.ts";
export const encodeBase64 = (str: string): string => {
if (str === null) {
throw new TypeError('1st argument of "encodeBase64" should not be null.')
}
try {
const encoder = new TextEncoder()
const bytes = encoder.encode(str)
return btoa(String.fromCharCode(...bytes))
} catch {}
try {
return Buffer.from(str).toString('base64')
} catch (e) {
console.error('If you want to do "encodeBase64", polyfill "buffer" module.')
throw e
}
}
export const decodeBase64 = (str: string): string => {
if (str === null) {
throw new TypeError('1st argument of "decodeBase64" should not be null.')
}
try {
const text = atob(str)
const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0)))
const decoder = new TextDecoder()
return decoder.decode(bytes)
} catch {}
try {
return Buffer.from(str, 'base64').toString()
} catch (e) {
console.error('If you want to do "decodeBase64", polyfill "buffer" module.')
throw e
}
}
export const encodeBase64URL = (str: string): string => {
return encodeBase64(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
}
export const decodeBase64URL = (str: string): string => {
const pad = (s: string) => {
const diff = s.length % 4
if (diff === 2) {
return `${s}==`
}
if (diff === 3) {
return `${s}=`
}
return s
}
return decodeBase64(pad(str).replace(/-/g, '+').replace('_', '/'))
}
export const utf8ToUint8Array = (str: string): Uint8Array => {
const encoder = new TextEncoder()
return encoder.encode(str)
}
export const arrayBufferToBase64 = async (buf: ArrayBuffer): Promise<string> => {
if (typeof btoa === 'function') {
return btoa(String.fromCharCode(...new Uint8Array(buf)))
}
try {
return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64')
} catch (e) {}
return ''
}
export const arrayBufferToBase64URL = async (buf: ArrayBuffer) => {
return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
}