// @ts-check /** * Convert a `Uint8Array` to a URL-safe base64 string. * @param {Uint8Array} bytes * @returns {string} */ export const stringify = (bytes) => { const string = String.fromCharCode(...bytes); const base64 = btoa(string); return base64 .replaceAll("+", "-") .replaceAll("/", "_") .replaceAll("=", ""); }; /** * Convert a URL-safe base64 string to a `Uint8Array`. * Returns `null` if the string is invalid. * @param {string} text * @returns {null | Uint8Array} */ export const parse = (text) => { const normalizedText = text .replaceAll("-", "+") .replaceAll("_", "/") .replaceAll(" ", "+"); try { const string = atob(normalizedText); const bytes = new Uint8Array(string.length); for (let i = 0; i < string.length; i++) { bytes[i] = string.charCodeAt(i); } return bytes; } catch (_err) { return null; } };