encode.ts
This file
Path
src/utils/encode.ts
34 lines · 1.1 KiB · TypeScript
Last changed by
Merge pull request #2769 from honojs/nextYusuke Wadabefore adoptionacd3634
History of this fileTake it
The walk stopped after 200 commits: lines older than b0cac62 point at it.
Merge pull request #2769 from honojs/nextYusuke Wadabefore adoptionacd3634
lines 1–5why, one step back1/**2 * @module3 * Encode utility.4 */5refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62
lines 6–17why, one step back6export const decodeBase64Url = (str: string): Uint8Array => {7 return decodeBase64(str.replace(/_|-/g, (m) => ({ _: '/', '-': '+' }[m] ?? m)))8}910export const encodeBase64Url = (buf: ArrayBufferLike): string =>11 encodeBase64(buf).replace(/\/|\+/g, (m) => ({ '/': '_', '+': '-' }[m] ?? m))1213// This approach is written in MDN.14// btoa does not support utf-8 characters. So we need a little bit hack.15export const encodeBase64 = (buf: ArrayBufferLike): string => {16 let binary = ''17 const bytes = new Uint8Array(buf)Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
line 18why, one step back18 for (let i = 0, len = bytes.length; i < len; i++) {refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62
lines 19–34why, one step back19 binary += String.fromCharCode(bytes[i])20 }21 return btoa(binary)22}2324// atob does not support utf-8 characters. So we need a little bit hack.25export const decodeBase64 = (str: string): Uint8Array => {26 const binary = atob(str)27 const bytes = new Uint8Array(new ArrayBuffer(binary.length))28 const half = binary.length / 229 for (let i = 0, j = binary.length - 1; i <= half; i++, j--) {30 bytes[i] = binary.charCodeAt(i)31 bytes[j] = binary.charCodeAt(j)32 }33 return bytes34}