encode.test.ts
This file
Path
src/utils/encode.test.ts
61 lines · 2.0 KiB · TypeScript
Last changed by
chore(lint): ESLint v9 (#3393)Yusuke Wadabefore adoption5f78e4e
History of this fileTake it
The walk stopped after 200 commits: lines older than 81a1f07 point at it.
fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 1–61why, one step back1import { decodeBase64Url, encodeBase64Url } from './encode'23const toURLBase64 = (base64String: string): string =>4 base64String.replace(/\+|\//g, (m) => ({ '+': '-', '/': '_' }[m] ?? m))56const str2UInt8Array = (s: string): Uint8Array => {7 const buffer = new Uint8Array(new ArrayBuffer(s.length))8 for (let i = 0, len = buffer.byteLength; i < len; i++) {9 buffer[i] = s.charCodeAt(i)10 }11 return buffer12}1314describe('base64', () => {15 const utf8Encoder = new TextEncoder()16 describe.each([17 // basic18 [utf8Encoder.encode('Hello, 世界'), 'SGVsbG8sIOS4lueVjA=='],19 [utf8Encoder.encode('炎'), '54KO'],20 [utf8Encoder.encode('🔥'), '8J+UpQ=='],21 [22 utf8Encoder.encode('http://github.com/honojs/hono'),23 'aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8=',24 ],2526 // RFC 3548 examples27 [str2UInt8Array('\x14\xfb\x9c\x03\xd9\x7e'), 'FPucA9l+'],28 [str2UInt8Array('\x14\xfb\x9c\x03\xd9'), 'FPucA9k='],29 [str2UInt8Array('\x14\xfb\x9c\x03'), 'FPucAw=='],3031 // RFC 4648 examples32 [str2UInt8Array(''), ''],33 [str2UInt8Array('f'), 'Zg=='],34 [str2UInt8Array('fo'), 'Zm8='],35 [str2UInt8Array('foo'), 'Zm9v'],36 [str2UInt8Array('foob'), 'Zm9vYg=='],37 [str2UInt8Array('fooba'), 'Zm9vYmE='],38 [str2UInt8Array('foobar'), 'Zm9vYmFy'],3940 // Wikipedia examples41 [str2UInt8Array('sure.'), 'c3VyZS4='],42 [str2UInt8Array('sure'), 'c3VyZQ=='],43 [str2UInt8Array('sur'), 'c3Vy'],44 [str2UInt8Array('su'), 'c3U='],45 [str2UInt8Array('leasure.'), 'bGVhc3VyZS4='],46 [str2UInt8Array('easure.'), 'ZWFzdXJlLg=='],47 [str2UInt8Array('asure.'), 'YXN1cmUu'],48 [str2UInt8Array('sure.'), 'c3VyZS4='],49 ])('%s, %s', (stdDecoded, stdEncoded) => {50 it('encode', () => {51 const got = encodeBase64Url(stdDecoded)52 const want = toURLBase64(stdEncoded)53 expect(got).toStrictEqual(want)54 })55 it('decode', () => {56 const got = decodeBase64Url(toURLBase64(stdEncoded))57 const want = stdDecoded58 expect(got).toStrictEqual(want)59 })60 })61})