-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser.js
62 lines (51 loc) · 1.72 KB
/
browser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
'use strict';
/**
* Note on encode and replace functions:
* These is for Unicode support
* https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
*/
var encode = function (source, inputEncoding) {
var raw = '';
var data = [];
if (/^utf-?(8|16)$/i.test(inputEncoding) || !inputEncoding) {
encodeURIComponent(source).replace(/%([0-9A-F]{2})|./g, function(m, p1) {
data.push(p1 ? parseInt(p1, 16) : m.charCodeAt(0));
});
}
else if (inputEncoding === 'hex') {
source.replace(/[0-9A-F]{2}/gi, function(m) {
data.push(parseInt(m, 16));
});
}
else if (inputEncoding === 'binary') {
data = source;
}
else {
throw new Error('Invalid inputEncoding supplied');
}
// map + join generates invalid results for binary data
data.forEach(function(b) {
var hex = ('00' + b.toString(16)).slice(-2);
raw += String.fromCharCode('0x' + hex);
});
return btoa(raw);
};
var decode = function (encoded, outputEncoding) {
var data = Array.prototype.map.call(atob(encoded), function(c) {
return c.charCodeAt(0);
});
if (outputEncoding === 'binary')
return data;
if (outputEncoding === 'hex') {
return data.map(function(b) {
return ('00' + b.toString(16)).slice(-2);
}).join('');
}
if (/^utf-?(8|16)$/i.test(outputEncoding) || !outputEncoding) {
return decodeURIComponent(data.map(function(c) {
return '%' + ('00' + c.toString(16)).slice(-2);
}).join(''));
}
throw new Error('Invalid outputEncoding supplied');
};
module.exports = require('./common')(encode, decode);