Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/utils/lib/sandbox.js
blob: 93b77e053d2082a80090bfcf2f9771262361a009 (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394

// NOTE: this file is used is the bootstrapping process,
// so any "requires" must be accounted for in narwhal.js

exports.Loader = function (options) {
    var loader = {};
    var factories = options.factories || {};
    var paths = options.paths;
    var extensions = options.extensions || ["", ".js"];
    var timestamps = {};

    loader.resolve = exports.resolve;

    loader.find = function (topId) {
        for (var j = 0; j < extensions.length; j++) {
            var extension = extensions[j];
            if (system.fs.isAbsolute(topId)) {
                var path = topId + extension;
                if (system.fs.isFile(path)) {
                    return path;
                }
            }
            else {
                for (var i = 0; i < paths.length; i++) {
                    var path = system.fs.join(paths[i], topId + extension);
                    if (system.fs.isFile(path))
                        return path;
                }
            }
        }
        throw new Error("require error: couldn't find \"" + topId + '"');
    };

    loader.fetch = function (topId, path) {
        if (!path)
            path = loader.find(topId);
        if (typeof system.fs.mtime === "function")
            timestamps[path] = system.fs.mtime(path);
        var text = system.fs.read(path, {
            'charset': 'utf-8'
        });
        // we leave the endline so the error line numbers align
        text = text.replace(/^#[^\n]+\n/, "\n");
        return text;
    };

    loader.evaluate = function (text, topId) {
        if (system.evaluate) {
            var fileName = loader.find(topId);
            var factory = system.evaluate(text, fileName, 1);
            factory.path = fileName;
            return factory;
        } else {
            return new Function("require", "exports", "module", "system", "print", text);
        }
    };

    loader.load = function (topId) {
        if (!Object.prototype.hasOwnProperty.call(factories, topId)) {
            loader.reload(topId);
        } else if (typeof system.fs.mtime === "function") {
            var filePath = loader.find(topId);
            if (!Object.prototype.hasOwnProperty.call(timestamps, filePath) ||
                    system.fs.mtime(filePath) > timestamps[filePath])
                loader.reload(topId);
        }
        return factories[topId];
    };

    loader.reload = function (topId, path) {
        factories[topId] = loader.evaluate(loader.fetch(topId, path), topId);
    };

    loader.isLoaded = function (topId) {
        return Object.prototype.hasOwnProperty.call(factories, topId);
    };

    loader.paths = paths;
    loader.extensions = extensions;

    return loader;
};

exports.MultiLoader = function (options) {

    var factories = options.factories || {};

    var self = {};
    self.paths = options.paths || [];
    self.loader = options.loader || exports.Loader(options);
    self.loaders = options.loaders || [
        ["", self.loader],
        [".js", self.loader]
    ];

    self.resolve = exports.resolve;

    self.find = function (topId) {
        for (var j = 0; j < self.loaders.length; j++) {
            var pair = self.loaders[j];
            var extension = pair[0];
            var loader = pair[1];
            if (system.fs.isAbsolute(topId)) {
                var path = topId + extension;
                if (system.fs.isFile(path)) {
                    return [loader, path];
                }
            }
            else {
                for (var i = 0; i < self.paths.length; i++) {
                    var path = system.fs.join(self.paths[i], topId + extension);
                    if (system.fs.isFile(path)) {
                        return [loader, path];
                    }
                }
            }
        }
        throw "require error: couldn't find \"" + topId + '"';
    };

    self.load = function (topId) {
        if (!Object.prototype.hasOwnProperty.call(factories, topId))
            self.reload(topId);
        return factories[topId];
    };

    self.reload = function (topId) {
        var pair = self.find(topId);
        var loader = pair[0];
        var path = pair[1];
        loader.reload(topId, path);
        factories[topId] = loader.load(topId, path);
    };

    self.isLoaded = function (topId) {
        return Object.prototype.hasOwnProperty.call(factories, topId);
    };

    return self;
};

exports.AttenuatedLoader = function (loader) {
    var self = {};

    self.resolve = Object.freeze(function (id, baseId) {
        return loader.resolve(id, baseId);
    });

    self.fetch = Object.freeze(function (topId) {
        if (/\./.test(topId))
            throw new Error("Invalid module identifier");
        return loader.fetch(topId);
    });

    self.load = Object.freeze(function (topId, path) {
        if (/\./.test(topId))
            throw new Error("Invalid module identifier");
        return loader.load(topId, path);
    });

    self.reload = Object.freeze(function (topId) {
        if (/\./.test(topId))
            throw new Error("Invalid module identifier");
        return loader.reload(topId, path);
    });

    return Object.freeze(self);
};

exports.Sandbox = function (options) {
    options = options || {};
    var loader = options.loader;
    var sandboxSystem = options.system || system;
    var modules = options.modules || {};
    var debug = options.debug !== undefined ? !!options.debug : system.debug;

    // managed print free variable in the sandbox forwards
    // to system.print
    var print = options.print || function () {
        return sandboxSystem.print.apply(sandboxSystem, arguments);
    };

    var debugDepth = 0;
    var mainId;

    var sandbox = function (id, baseId, force, reload) {
        id = loader.resolve(id, baseId);

        /* populate memo with module instance */
        if (!Object.prototype.hasOwnProperty.call(modules, id) || force) {

            if (sandbox.debug) {
                debugDepth++;
                var debugAcc = "";
                for (var i = 0; i < debugDepth; i++) debugAcc += "+";
                system.print(debugAcc + " " + id, 'module');
            }

            var globals = {};
            if (sandbox.debug) {
                // record globals
                for (var name in global)
                    globals[name] = true;
            }
            
            if (!Object.prototype.hasOwnProperty.call(modules, id) || reload)
                modules[id] = {};
            var exports = modules[id];
            if (reload)
                loader.reload(id);

            var factory = null;
            try {
                factory = loader.load(id);
            } finally {
                // poor man's catch and rethrow (Rhino sets file/line to where the exception is thrown, not created)
                if (!factory) {
                    delete modules[id];
                    if (sandbox.debug)
                        debugDepth--;
                }
            }
            var require = Require(id, factory.path);
            var module = {
                'id': id,
                'path': factory.path
            };
            factory(require, exports, module, sandboxSystem, print);

            if (sandbox.debug) {
                // check for new globals
                for (var name in global)
                    if (!globals[name])
                        system.log.warn("NEW GLOBAL: " + name);
            }
        
            if (sandbox.debug) {
                var debugAcc = "";
                for (var i = 0; i < debugDepth; i++) debugAcc += "-";
                system.print(debugAcc + " " + id, 'module');
                debugDepth--;
            }

        }

        /* support curryId for modules in which it is requested */
        var exports = modules[id];
        var imports = {};
        var importsUsed = false;
        var curryUsed = false;
        for (var name in exports) {
            try {
                // This try/catch block is needed to handle wrapped Java
                // objects in Rhino.
                curryUsed = (
                    typeof exports[name] == "function" &&
                    exports[name].xNarwhalCurryId
                );
            } catch (exception) {};
            
            if (curryUsed) { 
                importsUsed = true;
                imports[name] = (function (callback) {
                    var curried = function () {
                        return callback.apply(
                            this,
                            [baseId].concat(Array.prototype.slice.call(arguments, 0))
                        );
                    };
                    curried.xNarwhalCurryId = callback;
                    return curried;
                })(exports[name].xNarwhalCurryId);
            } else {
                imports[name] = exports[name];
            }
        }

        if (!importsUsed)
            imports = exports;

        return imports;

    };

    var Require = function (baseId, fileName) { // XXX deprecated fileName
        var require = function (id) {
            //try {
                return sandbox(id, baseId);
            //} catch (exception) {
            //    if (exception.message)
            //        exception.message += ' in ' + baseId;
            //    throw exception;
            //}
        };
        require.id = baseId; // XXX deprecated
        require.loader = loader;
        require.fileName = fileName; // XXX deprecated
        require.main = mainId; // XXX deprecated
        require.paths = loader.paths;
        require.extensions = loader.extensions;
        /* offers a facility to request the module id
         * in which a function was imported */
        // XXX deprecated (will need to be moved to module object)
        require.xNarwhalCurryId = function (callback) {
            var curried = function () {
                return callback.apply(
                    this,
                    [baseId].concat(Array.prototype.slice.call(arguments))
                );
            };
            curried.curryId = callback;
            return curried;
        };
        return require;
    };

    sandbox.force = function (id) {
        return sandbox(id, '', true);
    };

    sandbox.main = function (id) {
        mainId = id;
        return sandbox(id);
    };

    sandbox.loader = loader;
    sandbox.system = system;
    sandbox.paths = loader.paths;
    sandbox.extensions = loader.extensions;
    sandbox.debug = debug;

    return sandbox;
};

exports.PrefixLoader = function (prefix, loader) {
    var self = this || {};

    self.resolve = function (id, baseId) {
        return loader.resolve(id, baseId);
    };

    /**** evaluate
    */
    self.evaluate = function (text, topId) {
        return loader.evaluate(text, prefix + topId);
    };

    /**** fetch
    */
    self.fetch = function (topId) {
        return loader.fetch(prefix + topId);
    };

    /**** load
    */
    self.load = function (topId) {
        return loader.load(prefix + topId);
    };

    return self;
};

exports.sandbox = function(main, system, options) {
    options = options || {};
    var prefix = options['prefix'];
    var loader = options['loader'] || require.loader;
    var modules = options['modules'] || {};
    var print = options['print'];
    var debug = options['debug'];
    if (!loader) throw new Error(
        "sandbox cannot operate without a loader, either explicitly " + 
        "provided as an option, or implicitly provided by the current " +
        "sandbox's 'loader' object."
    );
    if (prefix)
        loader = exports.PrefixLoader(prefix, loader);
    var sandbox = exports.Sandbox({
        modules: modules,
        loader: loader,
        system: system,
        print: print,
        debug: debug
    });
    return sandbox.main(main);
};

exports.resolve = function (id, baseId) {
    if (typeof id != "string")
        throw new Error("module id '" + id + "' is not a String");
    if (id.charAt(0) == ".") {
        id = system.fs.dirname(baseId) + "/" + id;
    }
    return system.fs.normal(id);
};