aboutsummaryrefslogtreecommitdiff
path: root/src/utils/base64.ts
blob: c0ef96aaa058bcac28246aa7b1a0747e75a24531 (plain) (blame)
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
export { textToBase64, base64ToText, isValidBase64, removePotentialDataAndMimePrefix };

function textToBase64(str: string) {
  return window.btoa(str);
}

function base64ToText(str: string) {
  if (!isValidBase64(str)) {
    throw new Error('Incorrect base64 string');
  }

  const cleanStr = removePotentialDataAndMimePrefix(str);

  try {
    return window.atob(cleanStr);
  } catch (_) {
    throw new Error('Incorrect base64 string');
  }
}

function removePotentialDataAndMimePrefix(str: string) {
  return str.replace(/^data:.*?;base64,/, '');
}

function isValidBase64(str: string) {
  const cleanStr = removePotentialDataAndMimePrefix(str);

  try {
    return window.btoa(window.atob(cleanStr)) === cleanStr;
  } catch (err) {
    return false;
  }
}