web.btoa.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. var $ = require('../internals/export');
  2. var global = require('../internals/global');
  3. var getBuiltIn = require('../internals/get-built-in');
  4. var uncurryThis = require('../internals/function-uncurry-this');
  5. var call = require('../internals/function-call');
  6. var fails = require('../internals/fails');
  7. var toString = require('../internals/to-string');
  8. var validateArgumentsLength = require('../internals/validate-arguments-length');
  9. var itoc = require('../internals/base64-map').itoc;
  10. var $btoa = getBuiltIn('btoa');
  11. var charAt = uncurryThis(''.charAt);
  12. var charCodeAt = uncurryThis(''.charCodeAt);
  13. var NO_ARG_RECEIVING_CHECK = !!$btoa && !fails(function () {
  14. $btoa();
  15. });
  16. var WRONG_ARG_CONVERSION = !!$btoa && fails(function () {
  17. return $btoa(null) !== 'bnVsbA==';
  18. });
  19. var WRONG_ARITY = !!$btoa && $btoa.length !== 1;
  20. // `btoa` method
  21. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  22. $({ global: true, bind: true, enumerable: true, forced: NO_ARG_RECEIVING_CHECK || WRONG_ARG_CONVERSION || WRONG_ARITY }, {
  23. btoa: function btoa(data) {
  24. validateArgumentsLength(arguments.length, 1);
  25. // `webpack` dev server bug on IE global methods - use call(fn, global, ...)
  26. if (NO_ARG_RECEIVING_CHECK || WRONG_ARG_CONVERSION || WRONG_ARITY) return call($btoa, global, toString(data));
  27. var string = toString(data);
  28. var output = '';
  29. var position = 0;
  30. var map = itoc;
  31. var block, charCode;
  32. while (charAt(string, position) || (map = '=', position % 1)) {
  33. charCode = charCodeAt(string, position += 3 / 4);
  34. if (charCode > 0xFF) {
  35. throw new (getBuiltIn('DOMException'))('The string contains characters outside of the Latin1 range', 'InvalidCharacterError');
  36. }
  37. block = block << 8 | charCode;
  38. output += charAt(map, 63 & block >> 8 - position % 1 * 8);
  39. } return output;
  40. }
  41. });