smartinject/ts/index.ts

61 lines
1.3 KiB
TypeScript
Raw Normal View History

2017-02-28 22:40:13 +00:00
import 'typings-global'
let Module = require('module');
import path = require('path');
import sourceMap = require('source-map-support');
import through2 = require('through2');
import vm = require('vm');
import { Transform } from 'stream'
sourceMap.install({
retrieveFile: function (path) {
if (cache[path]) {
2017-03-04 17:13:51 +00:00
return cache[path].contents.toString()
2017-02-28 22:40:13 +00:00
}
}
2017-03-04 17:13:51 +00:00
})
2017-02-28 22:40:13 +00:00
let cache = {};
2017-03-04 17:13:51 +00:00
let originalLoader = Module._extensions['.js']
2017-02-28 22:40:13 +00:00
Module._extensions['.js'] = function (module, filename) {
2017-03-04 17:13:51 +00:00
let file = cache[filename]
2017-02-28 22:40:13 +00:00
if (file) {
2017-03-04 17:13:51 +00:00
module._compile(file.contents.toString(), filename)
2017-02-28 22:40:13 +00:00
} else {
2017-03-04 17:13:51 +00:00
originalLoader.apply(this, arguments)
2017-02-28 22:40:13 +00:00
}
2017-03-04 17:13:51 +00:00
}
2017-02-28 22:40:13 +00:00
let originalModuleResolve = Module._resolveFilename
Module._resolveFilename = function (request, parent, isMain) {
let file = cache[request];
if (file) {
return request;
} else {
return originalModuleResolve.apply(this, arguments)
}
2017-03-04 17:13:51 +00:00
}
2017-02-28 22:40:13 +00:00
export let gulpPipe = function () {
return through2.obj(function (file, enc, cb) {
2017-07-28 16:19:06 +00:00
cache[file.path] = file
return cb(null, file)
2017-03-04 17:13:51 +00:00
})
}
2017-02-28 22:40:13 +00:00
export interface fileObject {
path: string
contents: Buffer
}
export let injectFileArray = async (fileArray: fileObject[]) => {
for (let fileObject of fileArray) {
cache[fileObject.path] = fileObject
}
return fileArray
}