3 const Module = require('module');
4 const crypto = require('crypto');
5 const fs = require('fs');
6 const path = require('path');
7 const vm = require('vm');
8 const os = require('os');
10 const hasOwnProperty = Object.prototype.hasOwnProperty;
12 //------------------------------------------------------------------------------
13 // FileSystemBlobStore
14 //------------------------------------------------------------------------------
16 class FileSystemBlobStore {
17 constructor(directory, prefix) {
18 const name = prefix ? slashEscape(prefix + '.') : '';
19 this._blobFilename = path.join(directory, name + 'BLOB');
20 this._mapFilename = path.join(directory, name + 'MAP');
21 this._lockFilename = path.join(directory, name + 'LOCK');
22 this._directory = directory;
26 has(key, invalidationKey) {
27 if (hasOwnProperty.call(this._memoryBlobs, key)) {
28 return this._invalidationKeys[key] === invalidationKey;
29 } else if (hasOwnProperty.call(this._storedMap, key)) {
30 return this._storedMap[key][0] === invalidationKey;
35 get(key, invalidationKey) {
36 if (hasOwnProperty.call(this._memoryBlobs, key)) {
37 if (this._invalidationKeys[key] === invalidationKey) {
38 return this._memoryBlobs[key];
40 } else if (hasOwnProperty.call(this._storedMap, key)) {
41 const mapping = this._storedMap[key];
42 if (mapping[0] === invalidationKey) {
43 return this._storedBlob.slice(mapping[1], mapping[2]);
48 set(key, invalidationKey, buffer) {
49 this._invalidationKeys[key] = invalidationKey;
50 this._memoryBlobs[key] = buffer;
55 if (hasOwnProperty.call(this._memoryBlobs, key)) {
57 delete this._memoryBlobs[key];
59 if (hasOwnProperty.call(this._invalidationKeys, key)) {
61 delete this._invalidationKeys[key];
63 if (hasOwnProperty.call(this._storedMap, key)) {
65 delete this._storedMap[key];
74 const dump = this._getDump();
75 const blobToStore = Buffer.concat(dump[0]);
76 const mapToStore = JSON.stringify(dump[1]);
79 mkdirpSync(this._directory);
80 fs.writeFileSync(this._lockFilename, 'LOCK', {flag: 'wx'});
82 // Swallow the exception if we fail to acquire the lock.
87 fs.writeFileSync(this._blobFilename, blobToStore);
88 fs.writeFileSync(this._mapFilename, mapToStore);
90 fs.unlinkSync(this._lockFilename);
98 this._storedBlob = fs.readFileSync(this._blobFilename);
99 this._storedMap = JSON.parse(fs.readFileSync(this._mapFilename));
101 this._storedBlob = Buffer.alloc(0);
102 this._storedMap = {};
105 this._memoryBlobs = {};
106 this._invalidationKeys = {};
114 function push(key, invalidationKey, buffer) {
115 buffers.push(buffer);
116 newMap[key] = [invalidationKey, offset, offset + buffer.length];
117 offset += buffer.length;
120 for (const key of Object.keys(this._memoryBlobs)) {
121 const buffer = this._memoryBlobs[key];
122 const invalidationKey = this._invalidationKeys[key];
123 push(key, invalidationKey, buffer);
126 for (const key of Object.keys(this._storedMap)) {
127 if (hasOwnProperty.call(newMap, key)) continue;
128 const mapping = this._storedMap[key];
129 const buffer = this._storedBlob.slice(mapping[1], mapping[2]);
130 push(key, mapping[0], buffer);
133 return [buffers, newMap];
137 //------------------------------------------------------------------------------
138 // NativeCompileCache
139 //------------------------------------------------------------------------------
141 class NativeCompileCache {
143 this._cacheStore = null;
144 this._previousModuleCompile = null;
147 setCacheStore(cacheStore) {
148 this._cacheStore = cacheStore;
153 const hasRequireResolvePaths = typeof require.resolve.paths === 'function';
154 this._previousModuleCompile = Module.prototype._compile;
155 Module.prototype._compile = function(content, filename) {
158 function require(id) {
159 return mod.require(id);
162 // https://github.com/nodejs/node/blob/v10.15.3/lib/internal/modules/cjs/helpers.js#L28
163 function resolve(request, options) {
164 return Module._resolveFilename(request, mod, false, options);
166 require.resolve = resolve;
168 // https://github.com/nodejs/node/blob/v10.15.3/lib/internal/modules/cjs/helpers.js#L37
169 // resolve.resolve.paths was added in v8.9.0
170 if (hasRequireResolvePaths) {
171 resolve.paths = function paths(request) {
172 return Module._resolveLookupPaths(request, mod, true);
176 require.main = process.mainModule;
178 // Enable support to add extra extension types
179 require.extensions = Module._extensions;
180 require.cache = Module._cache;
182 const dirname = path.dirname(filename);
184 const compiledWrapper = self._moduleCompile(filename, content);
186 // We skip the debugger setup because by the time we run, node has already
189 // `Buffer` is included for Electron.
190 // See https://github.com/zertosh/v8-compile-cache/pull/10#issuecomment-518042543
191 const args = [mod.exports, require, mod, filename, dirname, process, global, Buffer];
192 return compiledWrapper.apply(mod.exports, args);
197 Module.prototype._compile = this._previousModuleCompile;
200 _moduleCompile(filename, content) {
201 // https://github.com/nodejs/node/blob/v7.5.0/lib/module.js#L511
204 var contLen = content.length;
206 if (content.charCodeAt(0) === 35/*#*/ &&
207 content.charCodeAt(1) === 33/*!*/) {
212 // Find end of shebang line and slice it off
214 for (; i < contLen; ++i) {
215 var code = content.charCodeAt(i);
216 if (code === 10/*\n*/ || code === 13/*\r*/) break;
221 // Note that this actually includes the newline character(s) in the
222 // new output. This duplicates the behavior of the regular
223 // expression that was previously used to replace the shebang line
224 content = content.slice(i);
230 // create wrapper function
231 var wrapper = Module.wrap(content);
233 var invalidationKey = crypto
235 .update(content, 'utf8')
238 var buffer = this._cacheStore.get(filename, invalidationKey);
240 var script = new vm.Script(wrapper, {
245 produceCachedData: true,
248 if (script.cachedDataProduced) {
249 this._cacheStore.set(filename, invalidationKey, script.cachedData);
250 } else if (script.cachedDataRejected) {
251 this._cacheStore.delete(filename);
254 var compiledWrapper = script.runInThisContext({
261 return compiledWrapper;
265 //------------------------------------------------------------------------------
268 // https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98
269 // https://github.com/zertosh/slash-escape/blob/e7ebb99/slash-escape.js
270 //------------------------------------------------------------------------------
272 function mkdirpSync(p_) {
273 _mkdirpSync(path.resolve(p_), 0o777);
276 function _mkdirpSync(p, mode) {
278 fs.mkdirSync(p, mode);
280 if (err0.code === 'ENOENT') {
281 _mkdirpSync(path.dirname(p));
285 const stat = fs.statSync(p);
286 if (!stat.isDirectory()) { throw err0; }
294 function slashEscape(str) {
295 const ESCAPE_LOOKUP = {
302 const ESCAPE_REGEX = /[\\:/\x00z]/g; // eslint-disable-line no-control-regex
303 return str.replace(ESCAPE_REGEX, match => ESCAPE_LOOKUP[match]);
306 function supportsCachedData() {
307 const script = new vm.Script('""', {produceCachedData: true});
308 // chakracore, as of v1.7.1.0, returns `false`.
309 return script.cachedDataProduced === true;
312 function getCacheDir() {
313 const v8_compile_cache_cache_dir = process.env.V8_COMPILE_CACHE_CACHE_DIR;
314 if (v8_compile_cache_cache_dir) {
315 return v8_compile_cache_cache_dir;
318 // Avoid cache ownership issues on POSIX systems.
319 const dirname = typeof process.getuid === 'function'
320 ? 'v8-compile-cache-' + process.getuid()
321 : 'v8-compile-cache';
322 const version = typeof process.versions.v8 === 'string'
323 ? process.versions.v8
324 : typeof process.versions.chakracore === 'string'
325 ? 'chakracore-' + process.versions.chakracore
326 : 'node-' + process.version;
327 const cacheDir = path.join(os.tmpdir(), dirname, version);
331 function getParentName() {
332 // `module.parent.filename` is undefined or null when:
333 // * node -e 'require("v8-compile-cache")'
334 // * node -r 'v8-compile-cache'
335 // * Or, requiring from the REPL.
336 const parentName = module.parent && typeof module.parent.filename === 'string'
337 ? module.parent.filename
342 //------------------------------------------------------------------------------
344 //------------------------------------------------------------------------------
346 if (!process.env.DISABLE_V8_COMPILE_CACHE && supportsCachedData()) {
347 const cacheDir = getCacheDir();
348 const prefix = getParentName();
349 const blobStore = new FileSystemBlobStore(cacheDir, prefix);
351 const nativeCompileCache = new NativeCompileCache();
352 nativeCompileCache.setCacheStore(blobStore);
353 nativeCompileCache.install();
355 process.once('exit', () => {
356 if (blobStore.isDirty()) {
359 nativeCompileCache.uninstall();
363 module.exports.__TEST__ = {