| Index: test/stub-modules/common.js |
| diff --git a/test/stub-modules/common.js b/test/stub-modules/common.js |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..b1fc2b8b9b28c7306fad73e17f15ee4cd31a6ff7 |
| --- /dev/null |
| +++ b/test/stub-modules/common.js |
| @@ -0,0 +1,68 @@ |
| +let path = require("path"); |
| +let SandboxedModule = require("sandboxed-module"); |
| + |
| +let globals = { |
| + atob: data => new Buffer(data, "base64").toString("binary"), |
| + btoa: data => new Buffer(data, "binary").toString("base64"), |
| + Ci: {}, |
| + Cu: {import: () => { }}, |
| + navigator: {}, |
| + onShutdown: {add: () => { }}, |
| + Services: {obs: {addObserver: () => { }}}, |
| + XPCOMUtils: {generateQI: () => { }} |
| +}; |
| + |
| +function addExports(exports) |
| +{ |
| + // Unfortunately there's not a way for a source transformer to know the name |
| + // of the module being transformed. This means we must add all extra exports |
| + // to all modules, not ideal! |
| + let code = "if (!('EXPORT' in exports))\n" + |
| + " Object.defineProperty(exports, 'EXPORT', {get: () => EXPORT});"; |
| + |
| + return src => src + "\n" + exports. |
| + map(name => code.replace(/EXPORT/g, name)).join("\n"); |
| +} |
| + |
| +function rewriteRequires(source) |
| +{ |
| + // Taken from EasyPasswords |
|
kzar
2016/09/29 18:19:38
I modified this logic quite a bit since I took it
|
| + // https://github.com/palant/easypasswords/blob/master/gulp-utils.js |
| + let modules = new Set(["events", "io"]); |
| + return source.replace(/(\brequire\(["'])([^"']+)/g, (match, prefix, request) => |
| + { |
| + if (modules.has(request)) |
| + return prefix + request + ".js"; |
| + return match; |
| + }); |
| +} |
| + |
| +function libPath(moduleId) |
| +{ |
| + return path.resolve(__dirname, "..", "..", "lib", moduleId + ".js"); |
| +} |
| + |
| +exports.createSandbox = function(extraExports) |
| +{ |
| + // Shared require cache for this sandbox |
| + let cache = {}; |
| + |
| + let options = { |
| + cache: cache, |
| + globals: globals, |
| + sourceTransformers: [rewriteRequires] |
| + }; |
| + if (extraExports) |
| + options.sourceTransformers.push(addExports(extraExports)); |
| + |
| + return (moduleId, exports) => |
| + { |
| + let key = libPath(moduleId); |
| + |
| + // Only load modules which aren't already cached for this sandbox |
| + if (!(key in cache)) |
| + cache[key] = SandboxedModule.require(moduleId, options); |
| + |
| + return cache[key]; |
| + }; |
| +}; |