@igleite/tsutils
Version:
Uma coleção de utilitários em TypeScript para facilitar o desenvolvimento no dia a dia.
71 lines (70 loc) • 2.67 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Base64UrlUtils = void 0;
const string_utils_1 = require("../string/string-utils");
/**
* Fornece métodos para codificação e decodificação de strings em um formato Base64 seguro para URLs.
* A solução foi copiada de: [Stack Overflow](https://stackoverflow.com/questions/11743160/how-do-i-encode-and-decode-a-base64-string).
*
* @see https://stackoverflow.com/a/60738564
*/
class Base64UrlUtils {
/**
* Codifica a string especificada em um formato Base64 seguro para URLs.
*
* @example
* ```javascript
* const encoded = Base64Url.encode('Hello, World!');
* console.log(encoded); // Saída: SGVsbG8sIFdvcmxkIQ
* ```
*
* @param {string} text - A string a ser codificada.
* @returns {string} Uma string codificada em formato Base64 seguro para URLs.
*/
static encode(text) {
try {
if (string_utils_1.StringUtils.isNullOrEmpty(text)) {
return string_utils_1.StringUtils.Empty;
}
const base64 = btoa(unescape(encodeURIComponent(text))); // Converte para Base64
return base64.replace(/=+$/, '') // Remove '=' no final
.replace(/\+/g, '-') // Substitui '+' por '-'
.replace(/\//g, '_'); // Substitui '/' por '_'
}
catch (_a) {
return string_utils_1.StringUtils.Empty;
}
}
/**
* Decodifica a string codificada em formato Base64 seguro para URLs.
*
* @example
* const decoded = Base64Url.decode('SGVsbG8sIFdvcmxkIQ');
* console.log(decoded); // Saída: Hello, World!
*
* @param {string} text - A string codificada a ser decodificada.
* @returns {string} A string original decodificada.
*/
static decode(text) {
try {
if (string_utils_1.StringUtils.isNullOrEmpty(text)) {
return string_utils_1.StringUtils.Empty;
}
let base64 = text.replace(/-/g, '+') // Substitui '-' por '+'
.replace(/_/g, '/'); // Substitui '_' por '/'
switch (base64.length % 4) {
case 2:
base64 += '==';
break;
case 3:
base64 += '=';
break;
}
return decodeURIComponent(escape(atob(base64))); // Decodifica de Base64
}
catch (_a) {
return string_utils_1.StringUtils.Empty;
}
}
}
exports.Base64UrlUtils = Base64UrlUtils;