base64.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (function() {
  2. 'use strict';
  3. var object = (
  4. // #34: CommonJS
  5. typeof exports === 'object' && exports != null &&
  6. typeof exports.nodeType !== 'number' ?
  7. exports :
  8. // #8: web workers
  9. typeof self !== 'undefined' ?
  10. self :
  11. // #31: ExtendScript
  12. $.global
  13. );
  14. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15. function InvalidCharacterError(message) {
  16. this.message = message;
  17. }
  18. InvalidCharacterError.prototype = new Error ();
  19. InvalidCharacterError.prototype.name = 'InvalidCharacterError';
  20. // encoder
  21. // [https://gist.github.com/999166] by [https://github.com/nignag]
  22. object.btoa || (
  23. object.btoa = function(input) {
  24. var str = String (input);
  25. for (
  26. // initialize result and counter
  27. var block, charCode, idx = 0, map = chars, output = '';
  28. // if the next str index does not exist:
  29. // change the mapping table to "="
  30. // check if d has no fractional digits
  31. str.charAt (idx | 0) || (map = '=', idx % 1);
  32. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  33. output += map.charAt (63 & block >> 8 - idx % 1 * 8)
  34. ) {
  35. charCode = str.charCodeAt (idx += 3 / 4);
  36. if (charCode > 0xFF) {
  37. throw new InvalidCharacterError ("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
  38. }
  39. block = block << 8 | charCode;
  40. }
  41. return output;
  42. });
  43. // decoder
  44. // [https://gist.github.com/1020396] by [https://github.com/atk]
  45. object.atob || (
  46. object.atob = function(input) {
  47. var str = (String (input)).replace (/[=]+$/, ''); // #31: ExtendScript bad parse of /=
  48. if (str.length % 4 === 1) {
  49. throw new InvalidCharacterError ("'atob' failed: The string to be decoded is not correctly encoded.");
  50. }
  51. for (
  52. // initialize result and counters
  53. var bc = 0, bs, buffer, idx = 0, output = '';
  54. // get next character
  55. buffer = str.charAt (idx++); // eslint-disable-line no-cond-assign
  56. // character found in table? initialize bit storage and add its ascii value;
  57. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  58. // and if not first of each 4 characters,
  59. // convert the first 8 bits to one ascii character
  60. bc++ % 4) ? output += String.fromCharCode (255 & bs >> (-2 * bc & 6)) : 0
  61. ) {
  62. // try to find character in table (0-63, not found => -1)
  63. buffer = chars.indexOf (buffer);
  64. }
  65. return output;
  66. });
  67. } ());