michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: "use strict"; michael@0: michael@0: module.metadata = { michael@0: "stability": "unstable" michael@0: }; michael@0: michael@0: const { Cu } = require("chrome"); michael@0: michael@0: // Passing an empty object as second argument to avoid scope's pollution michael@0: const { atob, btoa } = Cu.import("resource://gre/modules/Services.jsm", {}); michael@0: michael@0: function isUTF8(charset) { michael@0: let type = typeof charset; michael@0: michael@0: if (type === "undefined") michael@0: return false; michael@0: michael@0: if (type === "string" && charset.toLowerCase() === "utf-8") michael@0: return true; michael@0: michael@0: throw new Error("The charset argument can be only 'utf-8'"); michael@0: } michael@0: michael@0: exports.decode = function (data, charset) { michael@0: if (isUTF8(charset)) michael@0: return decodeURIComponent(escape(atob(data))) michael@0: michael@0: return atob(data); michael@0: } michael@0: michael@0: exports.encode = function (data, charset) { michael@0: if (isUTF8(charset)) michael@0: return btoa(unescape(encodeURIComponent(data))) michael@0: michael@0: return btoa(data); michael@0: }