encode.ts
This file
Path
src/utils/encode.ts
29 lines · 1.0 KiB · TypeScript
Last changed by
Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
History of this fileTake it
The walk stopped after 200 commits: lines older than 43749a0 point at it.
feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0
lines 1–12why, one step back1export const decodeBase64Url = (str: string): Uint8Array => {2 return decodeBase64(str.replace(/_|-/g, (m) => ({ _: '/', '-': '+' }[m] ?? m)))3}45export const encodeBase64Url = (buf: ArrayBufferLike): string =>6 encodeBase64(buf).replace(/\/|\+/g, (m) => ({ '/': '_', '+': '-' }[m] ?? m))78// This approach is written in MDN.9// btoa does not support utf-8 characters. So we need a little bit hack.10export const encodeBase64 = (buf: ArrayBufferLike): string => {11 let binary = ''12 const bytes = new Uint8Array(buf)Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
line 13why, one step back13 for (let i = 0, len = bytes.length; i < len; i++) {feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0
lines 14–29why, one step back14 binary += String.fromCharCode(bytes[i])15 }16 return btoa(binary)17}1819// atob does not support utf-8 characters. So we need a little bit hack.20export const decodeBase64 = (str: string): Uint8Array => {21 const binary = atob(str)22 const bytes = new Uint8Array(new ArrayBuffer(binary.length))23 const half = binary.length / 224 for (let i = 0, j = binary.length - 1; i <= half; i++, j--) {25 bytes[i] = binary.charCodeAt(i)26 bytes[j] = binary.charCodeAt(j)27 }28 return bytes29}