/
modules.js
51 lines (43 loc) · 1.36 KB
/
modules.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
/*!
* CPM - Couch Package Manager
* Copyright (c) 2010 Caolan McMahon
* MIT Licensed
*/
/**
* Module dependencies
*/
var path = require('path'),
async = require('../deps/async'),
Script = process.binding('evals').Script;
/**
* Loads a commonjs module from the loaded design documents, returning
* the exported properties. The current_dir and target parameters are not the
* path of the module on the filesystem, but rather the path of the module
* within couchdb.
*
* @param {Object} module_cache
* @param {Object} packages
* @param {String} current_dir
* @param {String} target
*/
exports.require = function (module_cache, packages, current_dir, target) {
var p = path.normalize(path.join(current_dir, target));
if (module_cache[p]) return module_cache[p];
var nodes = p.split('/').slice(1);
var content = nodes.reduce(function (a, x) {
if (a[x] === undefined) {
throw new Error('Could not require module: ' + target);
}
return a = a[x];
}, packages);
var sandbox = {
module: {exports: {}},
require: async.apply(
exports.require, module_cache, packages, path.dirname(p)
)
};
sandbox.exports = sandbox.module.exports;
var s = new Script(content).runInNewContext(sandbox);
module_cache[p] = sandbox.module.exports;
return module_cache[p];
};