class Base64Encoder {
static encode(str) {
return btoa(unescape(encodeURIComponent(str)));
}
static decode(base64) {
try {
return decodeURIComponent(escape(atob(base64)));
} catch (e) {
return null;
}
}
static encodeUrlSafe(str) {
return this.encode(str)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
static decodeUrlSafe(base64) {
base64 = base64.replace(/-/g, '+').replace(/_/g, '/');
const padding = (4 - (base64.length % 4)) % 4;
base64 += '='.repeat(padding);
return this.decode(base64);
}
static isValid(base64) {
if (!base64 || base64.length === 0) return false;
const base64Regex = /^[A-Za-z0-9+\/]*={0,2}$/;
return base64Regex.test(base64);
}
}
module.exports = Base64Encoder;