UNPKG

2.83 kBJavaScriptView Raw
1var structr = require("structr"),
2dref = require("dref"),
3EventEmitter = require("events").EventEmitter,
4async = require("async"),
5LoaderFactory = require("./loaderFactory"),
6LoaderCollection = require("./collections/loaders"),
7PluginCollection = require("./collections/plugins"),
8Resolver = require("./resolver"),
9outcome = require("outcome");
10
11module.exports = structr(EventEmitter, {
12
13 /**
14 */
15
16 "__construct": function(plugInto, fs, loaders) {
17 this._params = {};
18 this._fs = fs;
19 this._loaders = new LoaderCollection();
20 this._plugins = new PluginCollection(plugInto, this);
21 this.loaderFactory = new LoaderFactory(this._plugins, loaders);
22 this.resolver = new Resolver(this);
23 },
24
25 /**
26 * returns params, or sets params. Note that you can
27 * deeply reference a param - this helps avoid null exceptions
28 */
29
30 "params": function(keyOrParams, value) {
31 if(!arguments.length) return this._params;
32 if(arguments.length === 1) {
33 if(typeof keyOrParams === "object") {
34 for(var key in keyOrParams) {
35 this.params(key, keyOrParams[key]);
36 }
37 return this;
38 }
39
40 return dref.get(this._params, keyOrParams);
41 }
42 dref.set(this._params, keyOrParams, value);
43 return this;
44 },
45
46 /**
47 * extend onto this loader. Useful for doing stuff like adding
48 * custom loaders e.g dnode
49 */
50
51 "use": function(extension) {
52 extension(this);
53 return this;
54 },
55
56 /**
57 * adds plugins to be loaded in on .load()
58 */
59
60 "require": function() {
61 var req = this._loaders, self = this;
62 Array.prototype.slice.call(arguments, 0).forEach(function(dep) {
63 req.add(self.loaderFactory.getLoader(dep));
64 });
65 return this;
66 },
67
68 /**
69 */
70
71 "paths": function() {
72 return this.resolver.paths.apply(this.resolver, arguments);
73 },
74
75 /**
76 * return one plugin
77 */
78
79 "module": function(search) {
80 return this._plugins.module(search);
81 },
82
83 /**
84 * return multiple plugins, OR loads based on the search. This is similar to
85 * require, but it's immediate.
86 */
87
88 "modules": function(search) {
89 return this._plugins.modules(search);
90 },
91
92 /**
93 */
94
95 "load": function(onLoad) {
96
97 if(onLoad) {
98 this.once("ready", onLoad);
99 }
100
101 //cannot reload.
102 if(this._loading) return this;
103 this._loading = true;
104
105 var self = this, on = outcome.error(onLoad);
106
107 //first load in the sources where the plugins live - need to unravel shit
108 this._loaders.load(on.success(function() {
109
110 //finally, load the plugins - this should be instant.
111 self._plugins.load(on.success(function(err) {
112
113 if(err) console.error(err.stack)
114
115 //apply this exports to this loader, and finish!
116 self.exports = self._plugins.exports;
117
118 //notify any listeners
119 self.emit("ready", null, self.exports);
120 }));
121 }));
122
123 return this;
124 }
125});