-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
373 lines (313 loc) · 11.2 KB
/
index.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
'use strict';
const Compiler = require('google-closure-compiler').compiler;
const {getNativeImagePath} = require('google-closure-compiler/lib/utils');
const Promise = require('bluebird');
const childProcess = require('child_process');
const fs = Promise.promisifyAll(require('fs'));
const path = require('path');
const pythonCmd = 'python';
const closureLibPath = path.dirname(require.resolve(path.join('google-closure-library', 'package.json'), {
// try cwd first to get the version required by the application
paths: [process.cwd(), __dirname]
}));
const closureSrcPath = path.join(closureLibPath, 'closure', 'goog');
const closureBuilder = path.join(__dirname, 'closure', 'closurebuilder.py');
const depsWriter = path.join(__dirname, 'closure', 'depswriter.py');
/**
* Run the Closure Compiler with the provided options.
* @param {Object} options The compiler options.
* @return {Promise} A promise that resolves when compilation is finished.
*/
const compile = function(options) {
const gccPackage = require('google-closure-compiler/package.json');
console.log(`Closure Compiler version: ${gccPackage.version}`);
const compiler = new Compiler(options);
const useNative = !!process.env.OPENSPHERE_CLOSURE_USE_NATIVE;
if (useNative) {
// Use native build of compiler to avoid a Java dependency. This is
// slightly slower for large numbers of files
const nativePath = getNativeImagePath();
if (nativePath) {
compiler.JAR_PATH = null;
compiler.javaPath = nativePath;
} else {
const platformMap = {
'linux': 'linux',
'darwin': 'osx',
'win32': 'windows'
};
const platform = platformMap[process.platform];
console.warn(`Could not find google-closure-compiler-${platform}/compiler! Falling back to Java version.`);
}
}
return new Promise(function(resolve, reject) {
compiler.run((exitCode, stdOut, stdErr) => {
if (exitCode) {
process.stderr.write(stdErr, () => reject(exitCode));
} else {
process.stderr.write(stdErr);
process.stdout.write(stdOut);
resolve();
}
});
});
};
/**
* Create a Closure manifest.
* @param {Object} options The Closure compiler options
* @param {string} basePath The base path
* @return {Promise} A promise that resolves to the generated manifest
*/
const createManifest = function(options, basePath) {
basePath = basePath || options.basePath;
if (!closureBuilder || !fs.existsSync(closureBuilder)) {
return Promise.reject('Could not locate closurebuilder.py!');
}
const roots = options.js.filter(notExclude).map(mapRoot);
const namespaces = options.entry_point.map(mapNamespace);
const args = [closureBuilder, ...roots, ...namespaces];
console.log('Creating file manifest with Closure builder...');
return execPythonCmd(args).then(function(output) {
let files = output.split('\n').filter(function(file) {
return Boolean(file);
});
if (basePath) {
files = files.map(function(file) {
// resolve links in the file path
file = fs.realpathSync(file);
return path.relative(basePath, file);
});
}
return files;
});
};
/**
* Reads a manifest file from the Google Closure Compiler and converts each
* path to a relative path from the given base path
*
* @param {string} manifestPath The path to the GCC manifest file
* @param {string=} optBasePath Optional base path. If not set, the file paths will be unchanged.
* @return {Array<string>} The array of file paths listed in the manifest
*/
const readManifest = function(manifestPath, optBasePath) {
let files = fileToLines(manifestPath);
if (optBasePath) {
files = files.map(function(file) {
return path.relative(optBasePath, file);
});
}
return files;
};
/**
* Writes a debug application loader that defines Closure dependencies and bootstraps the application.
* @param {Object} options The Closure compiler options.
* @param {string} outputFile The output file.
* @return {Promise} A promise that resolves when the file is written.
*/
const writeDebugLoader = function(options, outputFile) {
if (!depsWriter || !fs.existsSync(depsWriter)) {
return Promise.reject('Could not locate depswriter.py!');
}
const roots = options.js.filter(notExclude).filter(notGoog).map(mapRootWithPrefix).filter((root) => !!root);
const args = [depsWriter, ...roots];
console.log('Creating debug application loader...');
return execPythonCmd(args).then(function(output) {
// bootstrap each entry_point namespace to load the application
const bootstrapNamespaces = options.entry_point.map(mapBootstrapNamespace).join(',');
// TODO: remove when https://github.com/google/closure-library/issues/1004 is addressed
const depLoadThrottleMixin = `(function() {
goog.DebugLoader_.prototype.maxLoading_ = 500;
var origLoadDeps = goog.DebugLoader_.prototype.loadDeps_;
goog.DebugLoader_.prototype.loadDeps_ = function() {
origLoadDeps.call(this);
if (this.loadingDeps_.length >= this.maxLoading_) {
this.pause_();
}
};
var origLoaded = goog.DebugLoader_.prototype.loaded_;
goog.DebugLoader_.prototype.loaded_ = function(dep) {
origLoaded.call(this, dep);
if (this.paused_ && this.loadingDeps_.length < this.maxLoading_) {
this.resume_();
}
};
})();`;
//
// If the module namespace already exists on window, goog.module.declareLegacyNamespace will cause the loader to
// replace the existing object with the module's exports. This will drop anything previously loaded in the
// namespace. To fix this problem, use the existing object from window as the module exports.
//
const assignExportsMixin = `(function() {
var getExistingExports = function() {
if (goog.moduleLoaderState_.moduleName) {
var moduleParts = goog.moduleLoaderState_.moduleName.split('.');
var current = window;
while (moduleParts.length && current.hasOwnProperty(moduleParts[0])) {
current = current[moduleParts.shift()];
if (!moduleParts.length) {
return current;
}
}
}
return undefined;
};
goog.loadModuleFromSource_ = /** @type {function(string):?} */ (function() {
'use strict';
var exports = {};
eval(arguments[0]);
// if declareLegacyNamespace was called, the module's exports will be set at the module's namespace on the global
// window object. if that object already exists, merge the exports into it and set that as the exports.
var __existingExports__ = getExistingExports();
if (goog.moduleLoaderState_.declareLegacyNamespace && __existingExports__ &&
Object.getPrototypeOf(exports) === Object.prototype) {
Object.assign(__existingExports__, exports);
exports = __existingExports__;
}
return exports;
});
})();`;
const bootstrapJs = `goog.bootstrap([${bootstrapNamespaces}]);`;
const fileContent = [
output,
depLoadThrottleMixin,
assignExportsMixin,
// force goog.modules to wait for legacy goog.provide files to load
'goog.Dependency.defer_ = true;',
bootstrapJs
];
console.log('Writing ' + outputFile);
return fs.writeFileAsync(outputFile, fileContent.join('\n'));
});
};
/**
* Turns a file into an array of lines
*
* @param {string} path The path to the file
* @return {Array<string>} The file split into lines
*/
const fileToLines = function(path) {
const manifest = fs.readFileSync(path, 'utf8');
return manifest.split(/[\r\n]+/).filter(function(item) {
return Boolean(item);
});
};
/**
* Filter out exclusion glob patterns.
* @param {string} pattern The pattern
* @return {boolean} If the pattern is an exclusion
*/
const notExclude = function(pattern) {
return !pattern.startsWith('!');
};
/**
* Filter out exclusion glob patterns.
* @param {string} pattern The pattern
* @return {boolean} If the pattern is an exclusion
*/
const notGoog = function(pattern) {
return pattern.indexOf('google-closure-library') === -1;
};
/**
* Convert an entry point to a namespace string for `goog.bootstrap`.
* @param {string} entry The entry point
* @return {boolean} The argument
*/
const mapBootstrapNamespace = function(entry) {
return `'${entry.replace(/^goog:/, '')}'`;
};
/**
* Convert an entry point to a `--namespace` argument for `closurebuilder.py`.
* @param {string} entry The entry point
* @return {boolean} The argument
*/
const mapNamespace = function(entry) {
return '--namespace=' + entry.replace(/^goog:/, '');
};
/**
* Convert a glob pattern to a `--root` argument for `closurebuilder.py`.
* @param {string} pattern The pattern
* @return {boolean} The argument
*/
const mapRoot = function(pattern) {
return '--root=' + pattern.replace(/\*\*\.js$/, '');
};
/**
* Convert a glob pattern to a `--root_with_prefix` argument for `depswriter.py`. If the pattern cannot be resolved
* to a directory, an empty string will be returned to avoid errors in depswriter.
* @param {string} pattern The pattern
* @return {boolean} The argument
*/
const mapRootWithPrefix = function(pattern) {
pattern = pattern.replace(/[^\\/]+\.js$/, '');
if (fs.existsSync(pattern)) {
const relPath = path.relative(closureSrcPath, pattern);
return `--root_with_prefix=${pattern} ${relPath}`;
}
return '';
};
/**
* Execute a Python command.
* @param {Array} args The arguments.
* @return {Promise} A promise that resolves to the command output, or is rejected if there is an error.
*/
const execPythonCmd = function(args) {
return new Promise(function(resolve, reject) {
console.log(pythonCmd, args);
const process = childProcess.spawn(pythonCmd, args);
let errorData = '';
let outputData = '';
// listen for source files
process.stdout.on('data', function(data) {
outputData += data.toString();
});
// listen for source files
process.stderr.on('data', function(data) {
data = data.toString().trim();
// the Python logging module logs to stderr by default, so even info
// messages will appear in stderr. detect these and write them to the
// console
if (data.startsWith(depsWriter)) {
console.log(data);
} else {
errorData += data;
}
});
process.on('error', function(err) {
reject(err.code === 'ENOENT' ? 'Python not found in path.' : (err.message || 'Command failed.'));
});
// handle python script complete
process.on('exit', function(code) {
if (code) {
reject(errorData);
} else {
resolve(outputData);
}
});
});
};
/**
* Writes a Google Closure deps file.
* @param {Object} options The Closure compiler options.
* @param {string} outputFile The output file.
* @return {Promise} A promise that resolves when the file is written.
*/
const writeDeps = function(options, outputFile) {
if (!depsWriter || !fs.existsSync(depsWriter)) {
return Promise.reject('Could not locate depswriter.py!');
}
const roots = options.js.filter(notExclude).filter(notGoog).map(mapRootWithPrefix).filter((root) => !!root);
const args = [depsWriter, ...roots];
console.log('Writing Closure deps...');
return execPythonCmd(args).then(function(output) {
console.log(`Writing ${outputFile}`);
return fs.writeFileAsync(outputFile, output);
});
};
module.exports = {
compile,
writeDebugLoader,
writeDeps,
createManifest,
fileToLines,
readManifest
};