base64.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. const toBinaryString = (text) => {
  16. if (typeof TextEncoder !== 'undefined') {
  17. const bytes = new TextEncoder().encode(text);
  18. let binary = '';
  19. bytes.forEach((byte) => {
  20. binary += String.fromCharCode(byte);
  21. });
  22. return binary;
  23. }
  24. return encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (_, hex) =>
  25. String.fromCharCode(parseInt(hex, 16)),
  26. );
  27. };
  28. export const encodeToBase64 = (value) => {
  29. const input = value == null ? '' : String(value);
  30. if (typeof window === 'undefined') {
  31. if (typeof Buffer !== 'undefined') {
  32. return Buffer.from(input, 'utf-8').toString('base64');
  33. }
  34. if (
  35. typeof globalThis !== 'undefined' &&
  36. typeof globalThis.btoa === 'function'
  37. ) {
  38. return globalThis.btoa(toBinaryString(input));
  39. }
  40. throw new Error(
  41. 'Base64 encoding is unavailable in the current environment',
  42. );
  43. }
  44. return window.btoa(toBinaryString(input));
  45. };