All files / utils base64.ts

100% Statements 50/50
92.11% Branches 35/38
100% Functions 14/14
100% Lines 48/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215                          36x             36x   36x 36x 2304x     36x       1494x   1494x     1494x           1494x     36x 42x     36x   3700x 3676x 3676x                 24x     24x             36x 84x     84x       1494x 1494x   1494x       1494x         1494x 1494x     36x 42x       36x   3700x     24x       24x 24x         160x           3516x         36x 84x     36x 84x                               131x   47x     84x                                 134x   50x     84x                                 66x                                       71x    
/**
 * base64.js
 * Dan Kogai (https://github.com/dankogai)
 * Licensed under the BSD 3-Clause License
 * https://github.com/dankogai/js-base64/blob/master/LICENSE.md
 *
 * Modified by Jay Fong
 */
 
type XToY = (value: string) => string
 
// 使用 global['Buffer'] 而不是 Buffer 以防止 webpack 等工具自动加 polyfill
const canUseBufferFrom =
  typeof global !== 'undefined' &&
  // @ts-expect-error https://github.com/microsoft/TypeScript/issues/39504
  typeof global['Buffer'] !== 'undefined' &&
  // @ts-expect-error https://github.com/microsoft/TypeScript/issues/39504
  typeof global['Buffer']['from'] === 'function'
 
const base64Chars =
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
 
const base64Table: { [key: string]: number } = {}
for (let i = 0; i < base64Chars.length; i++) {
  base64Table[base64Chars[i]] = i
}
 
const fromCharCode = String.fromCharCode
 
// binaryToAscii
function binaryToAsciiReplacer(str: string) {
  const padlen = [0, 2, 1][str.length % 3]
  const ord =
    (str.charCodeAt(0) << 16) |
    ((str.length > 1 ? str.charCodeAt(1) : 0) << 8) |
    (str.length > 2 ? str.charCodeAt(2) : 0)
  const chars = [
    base64Chars.charAt(ord >>> 18),
    base64Chars.charAt((ord >>> 12) & 63),
    padlen >= 2 ? '=' : base64Chars.charAt((ord >>> 6) & 63),
    padlen >= 1 ? '=' : base64Chars.charAt(ord & 63),
  ]
  return chars.join('')
}
const binaryToAscii: XToY =
  (typeof window !== 'undefined' && window.btoa) ||
  (value => value.replace(/[\s\S]{1,3}/g, binaryToAsciiReplacer))
 
// utf8ToBinary
const utf8ToBinaryRegExp = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g
function utf8ToBinaryReplacer(str: string) {
  if (str.length < 2) {
    const cc = str.charCodeAt(0)
    return cc < 0x80
      ? str
      : cc < 0x800
      ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))
      : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) +
        fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
        fromCharCode(0x80 | (cc & 0x3f))
  }
  const cc =
    0x10000 +
    (str.charCodeAt(0) - 0xd800) * 0x400 +
    (str.charCodeAt(1) - 0xdc00)
  return (
    fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) +
    fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) +
    fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
    fromCharCode(0x80 | (cc & 0x3f))
  )
}
const utf8ToBinary: XToY = value =>
  value.replace(utf8ToBinaryRegExp, utf8ToBinaryReplacer)
 
// utf8ToAscii
const utf8ToAscii: XToY = value => binaryToAscii(utf8ToBinary(value))
 
// asciiToBinary
function asciiToBinaryReplacer(str: string) {
  const len = str.length
  const padlen = len % 4
  const n =
    (len > 0 ? base64Table[str.charAt(0)] << 18 : 0) |
    (len > 1 ? base64Table[str.charAt(1)] << 12 : 0) |
    (len > 2 ? base64Table[str.charAt(2)] << 6 : 0) |
    (len > 3 ? base64Table[str.charAt(3)] : 0)
  const chars = [
    fromCharCode(n >>> 16),
    fromCharCode((n >>> 8) & 0xff),
    fromCharCode(n & 0xff),
  ]
  chars.length -= [0, 0, 2, 1][padlen]
  return chars.join('')
}
const asciiToBinary: XToY =
  (typeof window !== 'undefined' && window.atob) ||
  (value => value.replace(/\S{1,4}/g, asciiToBinaryReplacer))
 
// binaryToUtf8
const binaryToUtf8RegExp =
  /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g
function binaryToUtf8Replacer(str: string) {
  switch (str.length) {
    case 4:
      const cp =
        ((0x07 & str.charCodeAt(0)) << 18) |
        ((0x3f & str.charCodeAt(1)) << 12) |
        ((0x3f & str.charCodeAt(2)) << 6) |
        (0x3f & str.charCodeAt(3))
      const offset = cp - 0x10000
      return (
        fromCharCode((offset >>> 10) + 0xd800) +
        fromCharCode((offset & 0x3ff) + 0xdc00)
      )
    case 3:
      return fromCharCode(
        ((0x0f & str.charCodeAt(0)) << 12) |
          ((0x3f & str.charCodeAt(1)) << 6) |
          (0x3f & str.charCodeAt(2)),
      )
    default:
      return fromCharCode(
        ((0x1f & str.charCodeAt(0)) << 6) | (0x3f & str.charCodeAt(1)),
      )
  }
}
const binaryToUtf8: XToY = value =>
  value.replace(binaryToUtf8RegExp, binaryToUtf8Replacer)
 
// asciiToUtf8
const asciiToUtf8: XToY = value =>
  binaryToUtf8(asciiToBinary(value.replace(/=+$/, '')))
 
/**
 * 将给定的 UTF8 字符串编码为 base64 字符串。
 *
 * @public
 * @param value 要编码的 UTF8 字符串
 * @returns 返回编码后的 base64 字符串
 * @example
 * ```typescript
 * base64Encode('v') // => 'dg=='
 * base64Encode('龙') // => '6b6Z'
 * base64Encode('🐱') // => '8J+QsQ=='
 * ```
 */
export function base64Encode(value: string): string {
  if (canUseBufferFrom) {
    // @ts-expect-error https://github.com/microsoft/TypeScript/issues/39504
    return global['Buffer']['from'](value, 'utf8').toString('base64')
  }
 
  return utf8ToAscii(value)
}
 
/**
 * 将给定的 base64 字符串解码为 UTF8 字符串。
 *
 * @public
 * @param value 要解码的 base64 字符串
 * @returns 返回解码后的 UTF8 字符串
 * @example
 * ```typescript
 * base64Decode('dg==') // => 'v'
 * base64Decode('6b6Z') // => '龙'
 * base64Decode('8J+QsQ==') // => '🐱'
 * ```
 */
export function base64Decode(value: string): string {
  if (canUseBufferFrom) {
    // @ts-expect-error https://github.com/microsoft/TypeScript/issues/39504
    return global['Buffer']['from'](value, 'base64').toString('utf8')
  }
 
  return asciiToUtf8(value)
}
 
/**
 * 将给定的 UTF8 字符串编码为 URL 安全的 base64url 字符串。
 *
 * @public
 * @param value 要编码的 UTF8 字符串
 * @returns 返回编码后的 base64url 字符串
 * @example
 * ```typescript
 * base64UrlEncode('v') // => 'dg'
 * base64UrlEncode('龙') // => '6b6Z'
 * base64UrlEncode('🐱') // => '8J-QsQ'
 * ```
 */
export function base64UrlEncode(value: string): string {
  return base64Encode(value)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '')
}
 
/**
 * 将给定的 base64url 字符串解码为 UTF8 字符串。
 *
 * @public
 * @param value 要解码的 base64url 字符串
 * @returns 返回解码后的 UTF8 字符串
 * @example
 * ```typescript
 * base64UrlDecode('dg') // => 'v'
 * base64UrlDecode('6b6Z') // => '龙'
 * base64UrlDecode('8J-QsQ') // => '🐱'
 * ```
 */
export function base64UrlDecode(value: string): string {
  return base64Decode(value.replace(/-/g, '+').replace(/_/g, '/'))
}