smartinject/ts/injection.ts

77 lines
2.1 KiB
TypeScript
Raw Normal View History

2019-02-24 22:14:47 +00:00
const Module = require('module');
2019-02-24 22:11:26 +00:00
import path = require('path');
import sourceMap = require('source-map-support');
import vm = require('vm');
export const cache = {};
2019-02-24 22:14:47 +00:00
export const extensionMap: { [key: string]: () => string } = {};
const originalLoader = Module._extensions['.js'];
2019-02-24 22:11:26 +00:00
/**
* ensure sourcemap support works with the cache
*/
sourceMap.install({
2019-02-24 22:14:47 +00:00
retrieveFile: (path) => {
2019-02-24 22:11:26 +00:00
if (cache[path]) {
return cache[path].contents.toString();
} else if (cache[path + '.js']) {
return cache[path + '.js'].contents.toString();
}
}
});
Module._extensions['.js'] = function(module, filename) {
2019-02-24 22:14:47 +00:00
const file = cache[filename];
const file2 = cache[filename + '.js'];
2019-02-24 22:11:26 +00:00
if (file) {
module._compile(file.contents.toString(), filename);
} else if (file2) {
module._compile(file2.contents.toString(), filename);
} else {
originalLoader.apply(this, arguments);
}
};
2019-02-24 22:14:47 +00:00
for (const extension in extensionMap) {
if (extensionMap[extension]) {
2019-02-24 22:11:26 +00:00
Module._extensions[extension] = function(module, filename) {
2019-02-24 22:14:47 +00:00
const file = cache[filename];
const file2 = cache[filename + '.ts'];
2019-02-24 22:11:26 +00:00
if (file) {
module._compile(file.contents.toString(), filename);
} else if (file2) {
module._compile(file2.contents.toString(), filename);
} else {
originalLoader.apply(this, arguments);
}
};
}
}
2019-02-24 22:14:47 +00:00
const originalModuleResolve = Module._resolveFilename;
2019-02-24 22:11:26 +00:00
Module._resolveFilename = function(request, parent, isMain) {
let resolvedRequest: string;
if (parent && /^\./.test(request)) {
2019-02-24 22:14:47 +00:00
const resolvedDir = path.parse(parent.filename).dir;
2019-02-24 22:11:26 +00:00
resolvedRequest = path.join('/', resolvedDir, request);
} else {
resolvedRequest = request;
}
// uncomment for testing
/* if (/[yourTestFilenameHere.js]/.test(request)) {
console.log('resolvedRequest:' + resolvedRequest)
console.log(parent)
} */
2019-02-24 22:14:47 +00:00
const file = cache[resolvedRequest];
const file2 = cache[resolvedRequest + '.js'];
2019-02-24 22:11:26 +00:00
if (file || file2) {
return resolvedRequest;
} else {
return originalModuleResolve.apply(this, arguments);
}
};