UNPKG

@toruslabs/metadata-helpers

Version:
66 lines (62 loc) 2.08 kB
'use strict'; var bytes = require('./bytes.js'); /** * Pad a string to a multiple of segment length (4 for base64url). * @param input - The string to pad. * @returns The padded string. */ function padString(input) { const segmentLength = 4; const diff = input.length % segmentLength; if (!diff) { return input; } return input + "=".repeat(segmentLength - diff); } /** * Encode a string or Uint8Array to a base64url string. * @param input - The string (only support utf8 encoding) or Uint8Array to encode. * @returns The base64url string. */ function encodeBase64Url(input) { const bytes$1 = typeof input === "string" ? bytes.utf8ToBytes(input) : input; return fromBase64(bytes.bytesToBase64(bytes$1)); } /** * Decode a base64url string to a string or Uint8Array. * @param base64url - The base64url string to decode. * @returns The decoded string or Uint8Array. */ function decodeBase64Url(base64url) { return bytes.bytesToUtf8(bytes.base64ToBytes(toBase64(base64url))); } /** * Convert a base64url string to a base64 string. * @param base64url - The base64url string or Uint8Array (will be converted to string utf8 encoding) to convert. * @returns The base64 string. */ function toBase64(base64url) { const urlString = base64url instanceof Uint8Array ? bytes.bytesToUtf8(base64url) : base64url; return padString(urlString).replace(/-/g, "+").replace(/_/g, "/"); } /** * Decode a base64 string to a base64url string. * @param base64 - The base64 string to decode. * @returns The base64url string. */ function fromBase64(base64) { return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); } /** * Convert a base64url string to a buffer-like object. * @param base64url - The base64url string to convert. * @returns The buffer-like object. */ function toBufferLike(base64url) { return bytes.base64ToBytes(toBase64(base64url)); } exports.decodeBase64Url = decodeBase64Url; exports.encodeBase64Url = encodeBase64Url; exports.fromBase64 = fromBase64; exports.toBase64 = toBase64; exports.toBufferLike = toBufferLike;