UNPKG

2.84 kBJavaScriptView Raw
1(function(global) {
2
3 if (global.denodify) return;
4
5 var process = {
6 platform: 'browser'
7 };
8
9 var __global = {};
10
11 function error(type, arg1, arg2) {
12 var msg;
13 switch(type) {
14 case 'resolve':
15 msg = 'Couldn\'t resolve module ' + arg1 + ' in ' + arg2; break;
16 case 'route':
17 msg = 'No file with route ' + arg1 + ' found.'; break;
18 case 'load':
19 msg = 'Module ' + arg1 + ' has not registered itself with denodify.'; break;
20 case 'incomplete':
21 msg = 'Denodify knows nothing about a module with index ' + arg1; break;
22 }
23 throw Error(msg);
24 }
25
26 //from node path:
27 function dirname(path) {
28 var splitPathRe =
29 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
30
31 var result = splitPathRe.exec(path).slice(1),
32 root = result[0],
33 dir = result[1];
34
35 if (!root && !dir) {
36 // No dirname whatsoever
37 return '.';
38 }
39
40 if (dir) {
41 // It has a dirname, strip trailing slash
42 dir = dir.substr(0, dir.length - 1);
43 }
44
45 return root + dir;
46 };
47
48 function require(index) {
49 var data = m[index].d;
50 if (data) return data.exports;
51 var func = m[index].f;
52 if (!func) error('load', m[index].route);
53 func(
54 function(moduleid) { //require
55 var requiredIndex = m[index].resolve[moduleid];
56 if (!requiredIndex) error('resolve', moduleid, m[index].filename);
57 return require(requiredIndex);
58 },
59 data = m[index].d = { exports: {} }, //module
60 data.exports , //exports
61 m[index].filename,//__filename
62 dirname(m[index].filename), //__dirname
63 process, //process
64 __global //global
65 );
66 return data.exports;
67 }
68
69 //###API
70
71 //###denodify
72 //Registers module with denodify on script load.
73 global.denodify = function (func, index) {
74 var module = m[index];
75 if (!module) error('incomplete', index);
76 m[index].f = func;
77 };
78
79 //###require
80 //Use this function to pull in or kickstart any defined nodejs modules from
81 //outside nodejs modules.
82 global.denodify.require = function(route) {
83 var index;
84 if (Object.keys(m).some(function(k) {
85 index = k;
86 return m[k].filename === route;
87 })) {
88 return require(index);
89 }
90 error('route', route);
91 return null;
92 };
93
94 //###debug
95 global.denodify.debug = function(__filename) {
96 console.log('modules\n', m);
97 };
98
99 var m, routeIndex, requirerModuleIdIndex;
100
101})(this);