How to base64 encode in datamapper js?

I’m trying to work on a solution to create Google Static Maps links via the datamapper. We need to sign the request and that needs to be base64 encoded. Trying to use btoa() fails. Is this possible in the data mapper?

Is there a reference to what parts of JS are available and what isn’t in the version implemented by Objectif Lune?

The btoa() method is generally called on the window scope which isn’t available in the data mapper.

Fear not…the btoa() function below can be used to encode any ASCII string. In addition, if your string contains unicode characters, then use the b64EncodeUnicode() function below instead which also calls the btoa() function:

//b64EncodeUnicode('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
//btoa('Hello World!'); //SGVsbG8gV29ybGQh
//b64EncodeUnicode('Hello World!'); //SGVsbG8gV29ybGQh
 function btoa(input) {
  var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g;

    input = String(input);
    if (/[^\0-\xFF]/.test(input)) {
      logger.error('String contains characters outside of the Latin1 range.',2);
    }
    var padding = input.length % 3;
    var output = '';
    var position = -1;
    var a;
    var b;
    var c;
    var d;
    var buffer;

    var length = input.length - padding;

    while (++position < length) {

      a = input.charCodeAt(position) << 16;
      b = input.charCodeAt(++position) << 8;
      c = input.charCodeAt(++position);
      buffer = a + b + c;

      output += (
        TABLE.charAt(buffer >> 18 & 0x3F) +
        TABLE.charAt(buffer >> 12 & 0x3F) +
        TABLE.charAt(buffer >> 6 & 0x3F) +
        TABLE.charAt(buffer & 0x3F)
      );
    }

    if (padding == 2) {
      a = input.charCodeAt(position) << 8;
      b = input.charCodeAt(++position);
      buffer = a + b;
      output += (
        TABLE.charAt(buffer >> 10) +
        TABLE.charAt((buffer >> 4) & 0x3F) +
        TABLE.charAt((buffer << 2) & 0x3F) +
        '='
      );
    } else if (padding == 1) {
      buffer = input.charCodeAt(position);
      output += (
        TABLE.charAt(buffer >> 2) +
        TABLE.charAt((buffer << 4) & 0x3F) +
        '=='
      );
    }

    return output;
  }
  
  
  function b64EncodeUnicode(str) {
    // first we use encodeURIComponent to get percent-encoded UTF-8,
    // then we convert the percent encodings into raw bytes which
    // can be fed into btoa.
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes(match, p1) {
            return String.fromCharCode('0x' + p1);
    }));
}

Thanks Rod. Excellent answer.