addon-sdk/source/lib/sdk/base64.js

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:5744c2308a33
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 "use strict";
6
7 module.metadata = {
8 "stability": "unstable"
9 };
10
11 const { Cu } = require("chrome");
12
13 // Passing an empty object as second argument to avoid scope's pollution
14 const { atob, btoa } = Cu.import("resource://gre/modules/Services.jsm", {});
15
16 function isUTF8(charset) {
17 let type = typeof charset;
18
19 if (type === "undefined")
20 return false;
21
22 if (type === "string" && charset.toLowerCase() === "utf-8")
23 return true;
24
25 throw new Error("The charset argument can be only 'utf-8'");
26 }
27
28 exports.decode = function (data, charset) {
29 if (isUTF8(charset))
30 return decodeURIComponent(escape(atob(data)))
31
32 return atob(data);
33 }
34
35 exports.encode = function (data, charset) {
36 if (isUTF8(charset))
37 return btoa(unescape(encodeURIComponent(data)))
38
39 return btoa(data);
40 }

mercurial