web.atob.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var globalThis = require('../internals/global-this');
  4. var getBuiltIn = require('../internals/get-built-in');
  5. var uncurryThis = require('../internals/function-uncurry-this');
  6. var call = require('../internals/function-call');
  7. var fails = require('../internals/fails');
  8. var toString = require('../internals/to-string');
  9. var validateArgumentsLength = require('../internals/validate-arguments-length');
  10. var c2i = require('../internals/base64-map').c2i;
  11. var disallowed = /[^\d+/a-z]/i;
  12. var whitespaces = /[\t\n\f\r ]+/g;
  13. var finalEq = /[=]{1,2}$/;
  14. var $atob = getBuiltIn('atob');
  15. var fromCharCode = String.fromCharCode;
  16. var charAt = uncurryThis(''.charAt);
  17. var replace = uncurryThis(''.replace);
  18. var exec = uncurryThis(disallowed.exec);
  19. var BASIC = !!$atob && !fails(function () {
  20. return $atob('aGk=') !== 'hi';
  21. });
  22. var NO_SPACES_IGNORE = BASIC && fails(function () {
  23. return $atob(' ') !== '';
  24. });
  25. var NO_ENCODING_CHECK = BASIC && !fails(function () {
  26. $atob('a');
  27. });
  28. var NO_ARG_RECEIVING_CHECK = BASIC && !fails(function () {
  29. $atob();
  30. });
  31. var WRONG_ARITY = BASIC && $atob.length !== 1;
  32. var FORCED = !BASIC || NO_SPACES_IGNORE || NO_ENCODING_CHECK || NO_ARG_RECEIVING_CHECK || WRONG_ARITY;
  33. // `atob` method
  34. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  35. $({ global: true, bind: true, enumerable: true, forced: FORCED }, {
  36. atob: function atob(data) {
  37. validateArgumentsLength(arguments.length, 1);
  38. // `webpack` dev server bug on IE global methods - use call(fn, global, ...)
  39. if (BASIC && !NO_SPACES_IGNORE && !NO_ENCODING_CHECK) return call($atob, globalThis, data);
  40. var string = replace(toString(data), whitespaces, '');
  41. var output = '';
  42. var position = 0;
  43. var bc = 0;
  44. var length, chr, bs;
  45. if (string.length % 4 === 0) {
  46. string = replace(string, finalEq, '');
  47. }
  48. length = string.length;
  49. if (length % 4 === 1 || exec(disallowed, string)) {
  50. throw new (getBuiltIn('DOMException'))('The string is not correctly encoded', 'InvalidCharacterError');
  51. }
  52. while (position < length) {
  53. chr = charAt(string, position++);
  54. bs = bc % 4 ? bs * 64 + c2i[chr] : c2i[chr];
  55. if (bc++ % 4) output += fromCharCode(255 & bs >> (-2 * bc & 6));
  56. } return output;
  57. }
  58. });