├── .gitignore
├── .gitmodules
├── COPYING
├── README.md
├── bin.js
├── clients
├── module-client.js
└── test
│ └── demo.html
├── demo-server.js
├── module-compiler
├── INSTALL.md
├── bin.js
├── externs.js
├── module-compiler.js
├── package.json
└── third-party
│ └── closure-compiler
│ ├── COPYING
│ └── compiler.jar
├── module-graph.js
├── module-server.js
├── package.json
└── test
├── fixtures
├── build
│ ├── module$app.js
│ ├── module$app.js.map
│ ├── module$module$bar.js
│ ├── module$module$bar.js.map
│ ├── module$module$baz$foo.js
│ ├── module$module$baz$foo.js.map
│ ├── module$module$foo.js
│ ├── module$module$foo.js.map
│ ├── module$module.js
│ ├── module$module.js.map
│ ├── module$sub_app.js
│ ├── module$sub_app.js.map
│ ├── root.js
│ └── root.js.map
└── sample-module
│ ├── app.js
│ ├── module-graph.json
│ ├── module.js
│ ├── module
│ ├── bar.js
│ ├── baz
│ │ └── foo.js
│ └── foo.js
│ └── sub-app.js
├── test-module-client.js
├── test-module-graph.js
└── test-module-server.js
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "LABjs"]
2 | path = clients/third-party/LABjs
3 | url = git://github.com/getify/LABjs
4 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [2012] Google Inc
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Module Server
2 | ==============
3 |
4 | Module server is a system for efficient serving of CommonJS modules to web browsers. The core feature is that it supports *incremental loading* of modules and their dependencies with exactly 1 HTTP request per incremental load.
5 |
6 | This is a *reference implementation* that has not been battle-tested in production use. See our [presentation from JSConf EU 2012](https://docs.google.com/presentation/d/1Q44eWLI2qvZnmCF5oD2jCw-FFql9dYg36FE5CpbMlw4/preview) for more details.
7 |
8 | The serving system implements the following constraints:
9 |
10 | - Requesting a module initiates exactly 1 HTTP request
11 | - This single requests contains the requested module and all its dependencies.
12 | - Incremental loading (every module request after the first one) of additional modules only downloads dependencies that have not been requested already.
13 | - The client does not need to download a dependency tree to decide which additional dependencies to download.
14 |
15 | For many web applications serving all JavaScript in a single compiled binary may be a good enough, simple solution, more complex apps with large JS code bases will profit from only downloading code when it is needed. While AMD loaders such as [require.js](http://requirejs.org/) implement incremental loading as well, they often do so through recursive downloading of dependencies which may significantly degrade latency.
16 |
17 | Closure compiler supports both compilation of CommonJS and AMD modules. It should thus be possible to use this system as a production frontend for projects that use other systems such as require.js or browserify today.
18 |
19 | ## Source Maps
20 |
21 | By default all JS responses support [source maps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/) for optimal debugging with Chrome Dev Tools (Don't forget to activate source map support in the Dev Tools settings). We recommend to deactivate this for production use, if you only want to provide clients access to obfuscated JS
22 |
23 | ## Setup
24 |
25 | See [demo-server.js](demo-server.js) for an example server. You may want to adapt this to your individual serving stack (such as as for use within express). We recommend doing actual serving through a caching reverse proxy CDN network for minimal latency.
26 |
27 | ### Demo
28 |
29 | Run `node demo-server.js` then drag [clients/test/demo.html](clients/test/demo.html) to a browser window.
30 |
31 | ## Client
32 |
33 | [clients/module-client.js](clients/module-client.js) provides the in-browser module loader. It depends on $LAB.js but should be easily adaptable to most JS loaders.
34 |
35 | This will get you started:
36 |
37 |
38 |
39 |
40 |
43 |
44 | Whenever you want to do an incremental load of a module, replace `require('foo')` with `loadModule('foo', function(foo) { … })` and you are all set.
45 |
46 | ## Compiler
47 |
48 | [module-compiler/bin.js](module-compiler/bin.js) is a wrapper around closure compiler for compiling JS for serving with Module Server. Run with --help for usage. It supports watching a directory tree for automatic compilation when you change your sources and it ships with closure compiler for easy installation.
49 |
50 | Make sure you have the java binary in your path :)
51 |
52 | Example:
53 |
54 | node module-compiler/bin.js --module_path=./test/fixtures/sample-module --entry_module=app --output_path=../build/
55 |
56 | See the [INSTALL](module-compiler/INSTALL.md) instructions.
57 |
58 | ### Compilation
59 |
60 | Create a file called `app.js` (or whatever you like) and require all of your top-level modules in it (the ones you actually want to request from your application). This will ensure that everything gets compiled in one go.
61 |
62 | ## Fine print
63 |
64 | Pull requests are very much appreciated. Please sign the [Google Code contributor license agreement](http://code.google.com/legal/individual-cla-v1.0.html) (There is a convenient online form) before submitting.
65 |
66 |
71 |
--------------------------------------------------------------------------------
/bin.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | var exec = require('child_process').exec;
3 | var fs = require('fs');
4 |
5 | fs.exists(__dirname + '/clients/third-party/LABjs/LAB.js', function(exists) {
6 | runServer = function() {
7 | require(__dirname + '/demo-server');
8 | };
9 |
10 | if (exists) {
11 | runServer();
12 | return;
13 | }
14 |
15 | // JIC we haven't run the npm setup script
16 | var child = exec('cd ' + __dirname + ' && git submodule update',
17 | function (error, stdout, stderr) {
18 | console.log('stdout: ' + stdout);
19 | console.log('stderr: ' + stderr);
20 | if (error !== null) {
21 | console.log('exec error: ' + error);
22 | }
23 | }
24 | );
25 |
26 | child.on('close', runServer);
27 | });
28 |
29 |
30 |
--------------------------------------------------------------------------------
/clients/module-client.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2012 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /**
18 | * Creates a Module loader.
19 | * USAGE:
20 | * window.loadModule = ModuleServer('http://url./of/your/module/server/');
21 | * loadModule('your/module', function(yourModule) { … });
22 | * @param {string} urlPrefix URL prefix of your module server.
23 | * @param {function(string,Function)=} load OPTIONAL function to load JS
24 | * from a given URL, that fires a callback when the JS loaded. If
25 | * you do not provide this function, you need to include $LAB.js in the
26 | * current page. If you want to implement your own loader, make sure it
27 | * supports executing JS in load order (ideally without blocking).
28 | * @param {Function=} getUrl OPTIONAL function to create a URL given the
29 | * urlPrefix, the current module name and a list of modules that have
30 | * already been requested. You will need to provide this if your server
31 | * does not follow the conventions of demo-server.js.
32 | * @return {function(string, function(*)=)} Returns a function to load modules
33 | * The first param is the name of the module and the second param is a
34 | * callback that fires when the module loaded. It received the exports
35 | * object of the module as its first param.
36 | */
37 | function ModuleServer(urlPrefix, load, getUrl) {
38 | if (!urlPrefix) {
39 | urlPrefix = './';
40 | }
41 |
42 | if (!load) {
43 | // Provide a default load function. This function assumes that $LAB.js is
44 | // present in the current page.
45 | (function() {
46 | var lab = window.$LAB;
47 | load = function(url, cb) {
48 | lab.script(url).wait(cb);
49 | };
50 | })()
51 | }
52 |
53 | if (!getUrl) {
54 | getUrl = function(urlPrefix, module, requested) {
55 | return urlPrefix.replace(/\/$/, '') + '/' + encodeURIComponent(module) +
56 | (requested.length > 0 ? '/' + encodeURIComponent(
57 | requested.sort().join(',')) : '');
58 | };
59 | }
60 |
61 | var Server = function(urlPrefix) {
62 | this.urlPrefix = urlPrefix;
63 | this.requested = {};
64 | this.requestedList = [];
65 | this.loaded = {};
66 | };
67 |
68 | Server.prototype.load = function(module, cb) {
69 | var self = this;
70 | module = 'module$' + module.replace(/\//g, '$');
71 | if (this.loaded[module] || ModuleServer.m[module]) {
72 | if (cb) {
73 | cb(ModuleServer.m[module]);
74 | }
75 | return;
76 | }
77 | var userCb = cb;
78 | cb = function() {
79 | if (userCb) {
80 | userCb(ModuleServer.m[module]);
81 | }
82 | };
83 | if (this.requested[module]) {
84 | this.requested[module].push(cb);
85 | return;
86 | }
87 | var before = this.requestedList.slice();
88 | this.requestedList.push(module);
89 | var cbs = this.requested[module] = [cb];
90 | load(getUrl(this.urlPrefix, module, before), function() {
91 | self.loaded[module] = true;
92 | self.requested[module] = null;
93 | for (var i = 0; i < cbs.length; i++) {
94 | cbs[i]();
95 | }
96 | });
97 | };
98 |
99 | var instance = new Server(urlPrefix);
100 | function loadModule(module, cb) {
101 | instance.load(module, cb);
102 | };
103 | return loadModule;
104 | }
105 |
106 | // Registry for loaded modules.
107 | ModuleServer.m = {};
108 |
109 | if (typeof exports != 'undefined') {
110 | exports.ModuleServer = ModuleServer;
111 | }
112 |
--------------------------------------------------------------------------------
/clients/test/demo.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
Module Server Demo
5 |
Make sure to start node demo-server.js and then just open this
6 | file in your web browser
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/demo-server.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2012 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | var http = require('http');
18 | var fs = require('fs');
19 |
20 | var SOURCE_DIR = __dirname + '/test/fixtures/sample-module';
21 | var SOURCEMAP_PREFIX = '/_sourcemap';
22 | var SOURCEMAP_PATH_PREFIX_REGEX = /^\/_sourcemap\//;
23 | var ORIGINAL_SOURCE_PATH_PREFIX = 'http://127.0.0.1:1337/_js';
24 | var ORIGINAL_SOURCE_PATH_PREFIX_REGEX = /^\/_js\//;
25 |
26 | require('./module-server').from(SOURCE_DIR + '/../build',
27 | SOURCE_DIR + '/module-graph.json', run);
28 |
29 | function run(err, moduleServer) {
30 | if (err) {
31 | throw err;
32 | }
33 | function jsForPath(path, isSourceMapRequest, onJs) {
34 | path = path.replace(/^\//, '');
35 | var parts = path.split(/\//);
36 | var modules = decodeURIComponent(parts.shift()).split(/,/);
37 | var options = {};
38 | parts.forEach(function(part) {
39 | var pair = part.split(/=/);
40 | options[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
41 | });
42 | var exclude = null;
43 | if(options.exm) {
44 | exclude = options.exm.split(/,/);
45 | }
46 | return moduleServer(modules, exclude, onJs, {
47 | createSourceMap: isSourceMapRequest,
48 | sourceMapSourceRootUrlPrefix: ORIGINAL_SOURCE_PATH_PREFIX,
49 | debug: true,
50 | onLog: function() {
51 | console.log(arguments);
52 | }
53 | });
54 | }
55 |
56 | http.createServer(function (req, res) {
57 | var url = require('url').parse(req.url);
58 | // Load static files for demo
59 | switch(url.pathname) {
60 | case "/demo.html":
61 | fs.readFile(__dirname + '/clients/test/demo.html', 'utf8', function (err, html) {
62 | if(err) {
63 | throw err;
64 | } else {
65 | res.writeHead(200, {
66 | 'Content-Type': 'text/html',
67 | 'Content-Length': html.length
68 | });
69 | res.end(html, 'utf8');
70 | }
71 | });
72 | return;
73 | case "/third-party/LABjs/LAB.src.js":
74 | fs.readFile(__dirname + '/clients/third-party/LABjs/LAB.src.js', 'utf8', function (err, js) {
75 | if(err) {
76 | throw err;
77 | } else {
78 | res.writeHead(200, {
79 | 'Content-Type': 'application/javascript',
80 | });
81 | res.end(js, 'utf8');
82 | }
83 | });
84 | return;
85 | case "/module-client.js":
86 | fs.readFile(__dirname + '/clients/module-client.js', 'utf8', function (err, js) {
87 | if(err) {
88 | throw err;
89 | } else {
90 | res.writeHead(200, {
91 | 'Content-Type': 'application/javascript',
92 | });
93 | res.end(js, 'utf8');
94 | }
95 | });
96 | return;
97 | }
98 | console.log('Path ' + url.pathname);
99 | if (ORIGINAL_SOURCE_PATH_PREFIX_REGEX.test(url.pathname)) {
100 | var filename = SOURCE_DIR + '/' + url.pathname
101 | .replace(ORIGINAL_SOURCE_PATH_PREFIX_REGEX, '');
102 | fs.readFile(filename, 'utf8', function(err, js) {
103 | if (err) {
104 | throw err;
105 | } else {
106 | res.writeHead(200, {
107 | 'Content-Type': 'application/javascript',
108 | 'Content-Length': js.length,
109 | 'Pragma': 'no-cache'
110 | });
111 | res.end(js, 'utf8');
112 | }
113 | });
114 | return;
115 | }
116 | var isSourceMapRequest = false;
117 | if (SOURCEMAP_PATH_PREFIX_REGEX.test(url.pathname)) {
118 | isSourceMapRequest = true;
119 | url.pathname = url.pathname.replace(SOURCEMAP_PATH_PREFIX_REGEX, '/');
120 | }
121 | jsForPath(url.pathname, isSourceMapRequest, function(err, length, js,
122 | sourceMap) {
123 | if (err) {
124 | console.log('Error', err);
125 | if (err.statusCode) {
126 | res.writeHead(err.statusCode, {'Content-Type': 'text/plain'});
127 | res.end(err.message)
128 | } else {
129 | res.writeHead(500, {'Content-Type': 'text/plain'});
130 | res.end('Internal server error');
131 | }
132 | } else {
133 | if (isSourceMapRequest) {
134 | var map = JSON.stringify(sourceMap, null, ' ');
135 | res.writeHead(200, {
136 | 'Content-Type': 'application/json',
137 | 'Content-Length': map.length,
138 | 'Pragma': 'no-cache'
139 | });
140 | res.end(map, 'utf8');
141 | } else {
142 | var mapUrl = SOURCEMAP_PREFIX + url.pathname;
143 | res.writeHead(200, {
144 | 'Content-Type': 'application/javascript',
145 | 'Content-Length': length,
146 | 'SourceMap': mapUrl,
147 | 'X-SourceMap': mapUrl
148 | });
149 | res.end(js, 'utf8');
150 | }
151 | }
152 | });
153 | }).listen(1337, '127.0.0.1');
154 | console.log('Module server running at http://127.0.0.1:1337/');
155 | }
156 |
--------------------------------------------------------------------------------
/module-compiler/INSTALL.md:
--------------------------------------------------------------------------------
1 | Run `npm install` in this directory.
--------------------------------------------------------------------------------
/module-compiler/bin.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2012 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the 'License');
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an 'AS IS' BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | var opt = require('opt').create();
18 | var compiler = require('./module-compiler.js')
19 |
20 | var config = opt.configSync({
21 | process_common_js_modules: true,
22 | source_map_format: 'V3',
23 | // Triggers generation of one output file per CJS module.
24 | module: 'auto',
25 | create_source_map: '%outname%.map',
26 | externs: []
27 | }, []);
28 |
29 | function usage() {
30 | console.log('Example: node module-compiler/bin.js --module_path=' +
31 | './test/fixtures/sample-module --entry_module=app --output_path=../build/');
32 | opt.usage();
33 | process.exit(0);
34 | }
35 |
36 | var path;
37 | var watch = true;
38 |
39 | opt.option(['-h', '--help'], usage, 'This help screen.');
40 |
41 | opt.option(['-p', '--module_path'], function (p) {
42 | console.log(p);
43 | path = p.trim();
44 | }, 'The search path for modules.');
45 |
46 | opt.option(['-e', '--entry_module'], function (entryModule) {
47 | var filename = entryModule.trim();
48 | if (filename && !/\.js$/) {
49 | filename = filename + '.js';
50 | }
51 |
52 | config.common_js_entry_module = filename;
53 | }, 'The file name of the main module from which all dependencies are derived.');
54 |
55 | opt.option(['-o', '--output_path'], function (path) {
56 | config.module_output_path_prefix = (path.trim() || '').replace(/\/$/, '') + '/';
57 | config.output_module_dependencies = './module-graph.json';
58 | }, 'The path to the output directory for compiled modules.');
59 |
60 | opt.option(['--no-watch'], function () {
61 | watch = false;
62 | }, 'Do not keep this program alive and watch for changes in input modules.');
63 |
64 | opt.option(['--externs'], function (extern) {
65 | externs.push(extern);
66 | }, 'Path to an extern file for closure compiler.');
67 |
68 | opt.optionWith(process.argv);
69 | if (!path || path.length < 1 || !config.common_js_entry_module ||
70 | !config.module_output_path_prefix) {
71 | usage();
72 | }
73 |
74 | compiler.compile(path, config);
75 | if (watch) {
76 | compiler.watch(path, config);
77 | }
78 |
79 | // TODO get rid of the chdir dependency
80 |
--------------------------------------------------------------------------------
/module-compiler/externs.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2012 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | var window;
18 | // Just making sure, closure compiler by default likes to stomp on jQuery
19 | // which we can lead to bad developer experience.
20 | var $;
21 | var $LAB; // Part of the standard client.
22 |
23 | /**
24 | * Default recommended name for the function to load modules with ModuleServer.
25 | * Loads a module and then calls the callback once the loaded code is
26 | * available.
27 | * @param {string} name Name of the module to load. e.g. 'my/app'
28 | * @param {function(*)} cb Callback to be called when the module loaded.
29 | * The callback retrieves the exports object of the loaded module as the 1st
30 | * argument.
31 | */
32 | window.loadModule = function(name, cb) {};
33 |
34 | // Name of the default client
35 | var ModuleServer;
--------------------------------------------------------------------------------
/module-compiler/module-compiler.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2012 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the 'License');
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an 'AS IS' BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | var exec = require('child_process').exec;
18 |
19 | function compile(userArgs, cb) {
20 | var buildDir = userArgs.module_output_path_prefix
21 | var jsFiles = require('findit').sync('.').filter(function(filename) {
22 | return /\.js$/.test(filename) && !/^module\$/.test(filename);
23 | });
24 | var args = [
25 | '-jar', __dirname + '/third-party/closure-compiler/compiler.jar',
26 | // Adds default externs.
27 | '--externs', __dirname + '/externs.js',
28 | ];
29 | for (var key in userArgs) {
30 | // If the value is an array the key is appended one time per element in the
31 | // array.
32 | var vals = userArgs[key];
33 | if (!(vals instanceof Array)) {
34 | vals = [vals];
35 | }
36 | vals.forEach(function(val) {
37 | args.push('--' + key);
38 | // Closure compiler does not file --foo true.
39 | if (val !== true) {
40 | args.push(val);
41 | }
42 | })
43 | }
44 | jsFiles.forEach(function(filename) {
45 | args.push('--js', filename);
46 | });
47 | console.log('Compiling ' + jsFiles.join(', ') + '\n…');
48 | run(args);
49 |
50 | function run(args) {
51 | console.log('Running closure compiler: ' + JSON.stringify(args) + '\n…');
52 | var compiler = require('child_process').spawn('java', args, {
53 | stdio: 'inherit'
54 | });
55 |
56 | compiler.on('exit', function (code) {
57 | if (code === 0) {
58 | console.log('Compilation successful.');
59 | if (cb) {
60 | cb(null);
61 | }
62 | } else {
63 | console.log('Compilation failed.');
64 | if (cb) {
65 | cb(true);
66 | }
67 | }
68 | });
69 | }
70 | }
71 |
72 | var idle = true;
73 | var count = 0;
74 | function compileIfIdle(path, args) {
75 | if (count++ == 0) {
76 | // TODO remove this chdir.
77 | process.chdir(path);
78 | }
79 | if (idle) {
80 | idle = false;
81 | compile(args, function() {
82 | idle = true;
83 | });
84 | }
85 | }
86 |
87 | exports.compile = compileIfIdle;
88 | exports.watch = function(path, args) {
89 | function onChange(type, o) {
90 | if (o.path !== 'module-graph.json') { // TODO get rid of this.
91 | console.log(type + ': ' + o.path + (o.dir === true ? ' [DIR]' : ''))
92 | compileIfIdle(path, args);
93 | }
94 | }
95 | var Watcher = require('fs-watcher').watch;
96 |
97 | var watcher = new Watcher({
98 | root: '.'
99 | });
100 |
101 | watcher.on('create', onChange.bind(null, 'create'));
102 | watcher.on('change', onChange.bind(null, 'change'));
103 | watcher.on('delete', onChange.bind(null, 'delete'));
104 | watcher.on('error', function() {
105 | console.log('Error watching');
106 | });
107 |
108 | watcher.start();
109 | }
110 |
111 |
112 |
--------------------------------------------------------------------------------
/module-compiler/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name":"module-compiler",
3 | "version":"0.0.1",
4 | "description":"Compiles JavaScript for module-server",
5 | "keywords":["modules"],
6 | "author":"Google Inc.",
7 | "repository":{
8 | "url":"https://github.com/google/module-server.git",
9 | "type":"git"
10 | },
11 | "dependencies":{
12 | "fs-watcher": "0.2.1",
13 | "findit": "0.1.2",
14 | "opt": "0.0.9"
15 | },
16 | "bin": {
17 | "module-compiler": "./bin.js"
18 | },
19 | "bugs":{
20 | "url":"https://github.com/google/module-server/issues"
21 | },
22 | "main":"index",
23 | "engines":{
24 | "node":">= 0.8.0"
25 | }
26 | }
--------------------------------------------------------------------------------
/module-compiler/third-party/closure-compiler/COPYING:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [2012] Google Inc.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/module-compiler/third-party/closure-compiler/compiler.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/module-server/68c42d7a8621bee645d2e01e8a57d9ef7e7e6d5c/module-compiler/third-party/closure-compiler/compiler.jar
--------------------------------------------------------------------------------
/module-graph.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2012 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 |
18 | /**
19 | * Module for module graphs and dependency calculation.
20 | */
21 |
22 | var fs = require('fs');
23 |
24 | /**
25 | * Make a ModuleGraph from an object as it is output by closure compiler
26 | * when passed the TODO compiler flag.
27 | * @param {Array.