base64url.js 733 B

12345678910111213141516171819
  1. import { base64 } from "./base64.js";
  2. const BASE64URL_REGEX = /^[A-Za-z0-9_-]*$/;
  3. export function normalize(text) {
  4. return text.replace(/[\n\r\t ]/g, "");
  5. }
  6. export function is(text) {
  7. return typeof text === "string" && BASE64URL_REGEX.test(normalize(text));
  8. }
  9. export function encode(data, _options) {
  10. return base64.encode(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
  11. }
  12. export function decode(text, _options) {
  13. const normalized = normalize(text);
  14. if (!is(normalized)) {
  15. throw new TypeError("Input is not valid Base64Url text");
  16. }
  17. return base64.decode(base64.pad(normalized.replace(/-/g, "+").replace(/_/g, "/")));
  18. }
  19. export const base64url = { encode, decode, is, normalize };