All files / src/crypto/token-signer/base64url index.ts

90.9% Statements 20/22
50% Branches 2/4
100% Functions 5/5
90.9% Lines 20/22

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 4942x     42x 42x 42x   42x 12x     30x 30x 30x       32x     32x       42x 42x     42x       42x     42x   42x     42x 32x     42x        
import { base64ToBytes, bytesToBase64 } from 'micro-stacks/common';
 
function padString(input: string): string {
  const segmentLength = 4;
  const stringLength = input.length;
  const diff = stringLength % segmentLength;
 
  if (!diff) {
    return input;
  }
 
  const padLength = segmentLength - diff;
  const paddedStringLength = stringLength + padLength;
  return input.padEnd(paddedStringLength, '=');
}
 
function encode(input: string | Uint8Array): string {
  Iif (input instanceof Uint8Array) {
    return fromBase64(bytesToBase64(input));
  }
  return fromBase64(bytesToBase64(new TextEncoder().encode(input)));
}
 
function decode(base64url: string): string {
  const bytes = base64ToBytes(toBase64(base64url));
  return new TextDecoder().decode(bytes);
}
 
export function toBase64(base64url: string | Uint8Array): string {
  // We this to be a string so we can do .replace on it. If it's
  // already a string, this is a noop.
  let str: string;
  Iif (base64url instanceof Uint8Array) {
    str = new TextDecoder().decode(base64url);
  } else {
    str = base64url;
  }
  return padString(str).replace(/\-/g, '+').replace(/_/g, '/');
}
 
export function fromBase64(base64: string): string {
  return base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
 
export default {
  encode,
  decode,
};