OLD | NEW |
| (Empty) |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 // This file should define a function that returns a require() method that can | |
6 // be used to load JS modules. | |
7 // | |
8 // A module works the same as modules in node.js - JS script that populates | |
9 // an exports object, which is what require()ers get returned. The JS in a | |
10 // module will be run at most once as the exports result is cached. | |
11 // | |
12 // Modules have access to the require() function which can be used to load | |
13 // other JS dependencies, and requireNative() which returns objects that | |
14 // define native handlers. | |
15 // | |
16 // |bootstrap| contains the following fields: | |
17 // - GetSource(module): returns the source code for |module| | |
18 // - Run(source): runs the string os JS |source| | |
19 // - GetNative(nativeName): returns the named native object | |
20 (function(bootstrap) { | |
21 | |
22 function wrap(source) { | |
23 return "(function(require, requireNative, exports) {" + source + | |
24 "\n})"; | |
25 } | |
26 | |
27 function ModuleLoader() { | |
28 this.cache_ = {}; | |
29 }; | |
30 | |
31 ModuleLoader.prototype.run = function(id) { | |
32 var source = bootstrap.GetSource(id); | |
33 if (!source) { | |
34 return null; | |
35 } | |
36 var wrappedSource = wrap(source); | |
37 var f = bootstrap.Run(wrappedSource); | |
38 var exports = {}; | |
39 f(require, requireNative, exports); | |
40 return exports; | |
41 }; | |
42 | |
43 ModuleLoader.prototype.load = function(id) { | |
44 var exports = this.cache_[id]; | |
45 if (exports) { | |
46 return exports; | |
47 } | |
48 exports = this.run(id); | |
49 this.cache_[id] = exports; | |
50 return exports; | |
51 }; | |
52 | |
53 var moduleLoader = new ModuleLoader(); | |
54 | |
55 function requireNative(nativeName) { | |
56 return bootstrap.GetNative(nativeName); | |
57 } | |
58 | |
59 function require(moduleId) { | |
60 return moduleLoader.load(moduleId); | |
61 } | |
62 | |
63 return require; | |
64 }); | |
OLD | NEW |