|
| 1 | +import { |
| 2 | + stringToBase64URL, |
| 3 | + stringFromBase64URL, |
| 4 | + stringFromUTF8, |
| 5 | + codepointToUTF8, |
| 6 | +} from './base64url' |
| 7 | + |
| 8 | +const EXAMPLES = [ |
| 9 | + 'a', |
| 10 | + 'ab', |
| 11 | + 'abc', |
| 12 | + 'abcd', |
| 13 | + 'hello world', |
| 14 | + 'нешто на кирилица', |
| 15 | + 'something with emojis 🤙🏾 ', |
| 16 | + 'Supabaseは、オープンソースの Firebase 代替製品です。エンタープライズグレードのオープンソースツールを使って、Firebase の機能を構築しています。', |
| 17 | +] |
| 18 | + |
| 19 | +describe('stringToBase64URL', () => { |
| 20 | + EXAMPLES.forEach((example) => { |
| 21 | + test(`encode "${example}"`, () => { |
| 22 | + expect(stringToBase64URL(example)).toEqual(Buffer.from(example).toString('base64url')) |
| 23 | + }) |
| 24 | + }) |
| 25 | +}) |
| 26 | + |
| 27 | +describe('stringFromBase64URL', () => { |
| 28 | + EXAMPLES.forEach((example) => { |
| 29 | + test(`decode "${example}"`, () => { |
| 30 | + expect(stringFromBase64URL('\r\t\n ' + Buffer.from(example).toString('base64url'))).toEqual( |
| 31 | + example |
| 32 | + ) |
| 33 | + }) |
| 34 | + }) |
| 35 | + |
| 36 | + test('decode with invalid Base64-URL character', () => { |
| 37 | + expect(() => { |
| 38 | + stringFromBase64URL('*') |
| 39 | + }).toThrow(new Error(`Invalid Base64-URL character "*"`)) |
| 40 | + }) |
| 41 | +}) |
| 42 | + |
| 43 | +const BAD_UTF8 = [ |
| 44 | + [0xf8], // 11111000 |
| 45 | + [0xff], // 11111111 |
| 46 | + [0x80], // 10000000 |
| 47 | + [0xf8, 1], // 11110000 00000001 |
| 48 | + [0xe0, 1], // 11100000 00000001 |
| 49 | + [0xc0, 1], // 11100000 00000001 |
| 50 | +] |
| 51 | + |
| 52 | +describe('stringFromUTF8', () => { |
| 53 | + BAD_UTF8.forEach((example) => { |
| 54 | + test(`should recognize bad UTF-8 sequence ${example |
| 55 | + .map((x) => x.toString(16)) |
| 56 | + .join(' ')}`, () => { |
| 57 | + expect(() => { |
| 58 | + const state = { utf8seq: 0, codepoint: 0 } |
| 59 | + example.forEach((byte) => { |
| 60 | + // eslint-disable-next-line @typescript-eslint/no-empty-function |
| 61 | + stringFromUTF8(byte, state, () => {}) |
| 62 | + }) |
| 63 | + }).toThrow(new Error('Invalid UTF-8 sequence')) |
| 64 | + }) |
| 65 | + }) |
| 66 | +}) |
| 67 | + |
| 68 | +describe('codepointToUTF8', () => { |
| 69 | + test('invalid codepoints above 0x10ffff', () => { |
| 70 | + const invalidCodepoint = 0x10ffff + 1 |
| 71 | + expect(() => { |
| 72 | + codepointToUTF8(invalidCodepoint, () => { |
| 73 | + throw new Error('Should not becalled') |
| 74 | + }) |
| 75 | + }).toThrow(new Error(`Unrecognized Unicode codepoint: ${invalidCodepoint.toString(16)}`)) |
| 76 | + }) |
| 77 | +}) |
0 commit comments