Skip to content
Myr

encode.ts

This file

Path

src/utils/encode.ts

76 lines · 2.0 KiB · TypeScript

Last changed by

refactor(TypeScript): enable strict null check (#280)Yusuke Wadabefore adoptionb55eb2e

History of this file

Take it

feat(jwt): jwt middleware (#169)Minghebefore adoption3ed40d5

lines 1–69why, one step back
1export const encodeBase64 = (str: string): string => {
2 if (str === null) {3 throw new TypeError('1st argument of "encodeBase64" should not be null.')4 }5 try {6 const encoder = new TextEncoder()7 const bytes = encoder.encode(str)8 return btoa(String.fromCharCode(...bytes))9 } catch {}1011 try {12 return Buffer.from(str).toString('base64')13 } catch (e) {14 console.error('If you want to do "encodeBase64", polyfill "buffer" module.')15 throw e16 }17}1819export const decodeBase64 = (str: string): string => {20 if (str === null) {21 throw new TypeError('1st argument of "decodeBase64" should not be null.')22 }23 try {24 const text = atob(str)25 const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0)))26 const decoder = new TextDecoder()27 return decoder.decode(bytes)28 } catch {}2930 try {31 return Buffer.from(str, 'base64').toString()32 } catch (e) {33 console.error('If you want to do "decodeBase64", polyfill "buffer" module.')34 throw e35 }36}3738export const encodeBase64URL = (str: string): string => {39 return encodeBase64(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')40}4142export const decodeBase64URL = (str: string): string => {43 const pad = (s: string) => {44 const diff = s.length % 445 if (diff === 2) {46 return `${s}==`47 }48 if (diff === 3) {49 return `${s}=`50 }51 return s52 }5354 return decodeBase64(pad(str).replace(/-/g, '+').replace('_', '/'))55}5657export const utf8ToUint8Array = (str: string): Uint8Array => {58 const encoder = new TextEncoder()59 return encoder.encode(str)60}6162export const arrayBufferToBase64 = async (buf: ArrayBuffer): Promise<string> => {63 if (typeof btoa === 'function') {64 return btoa(String.fromCharCode(...new Uint8Array(buf)))65 }6667 try {68 return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64')69 } catch (e) {}

refactor(TypeScript): enable strict null check (#280)Yusuke Wadabefore adoptionb55eb2e

lines 70–71why, one step back
70
71 return ''

feat(jwt): jwt middleware (#169)Minghebefore adoption3ed40d5

lines 72–76why, one step back
72}
7374export const arrayBufferToBase64URL = async (buf: ArrayBuffer) => {75 return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')76}