hook.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /*
  2. Copyright 2012-2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. const path = require('path');
  6. const vm = require('vm');
  7. const appendTransform = require('append-transform');
  8. const originalCreateScript = vm.createScript;
  9. const originalRunInThisContext = vm.runInThisContext;
  10. const originalRunInContext = vm.runInContext;
  11. function transformFn(matcher, transformer, verbose) {
  12. return function(code, options) {
  13. options = options || {};
  14. // prior to 2.x, hookRequire returned filename
  15. // rather than object.
  16. if (typeof options === 'string') {
  17. options = { filename: options };
  18. }
  19. const shouldHook =
  20. typeof options.filename === 'string' &&
  21. matcher(path.resolve(options.filename));
  22. let transformed;
  23. let changed = false;
  24. if (shouldHook) {
  25. if (verbose) {
  26. console.error(
  27. 'Module load hook: transform [' + options.filename + ']'
  28. );
  29. }
  30. try {
  31. transformed = transformer(code, options);
  32. changed = true;
  33. } catch (ex) {
  34. console.error(
  35. 'Transformation error for',
  36. options.filename,
  37. '; return original code'
  38. );
  39. console.error(ex.message || String(ex));
  40. if (verbose) {
  41. console.error(ex.stack);
  42. }
  43. transformed = code;
  44. }
  45. } else {
  46. transformed = code;
  47. }
  48. return { code: transformed, changed };
  49. };
  50. }
  51. /**
  52. * unloads the required caches, removing all files that would have matched
  53. * the supplied matcher.
  54. * @param {Function} matcher - the match function that accepts a file name and
  55. * returns if that file should be unloaded from the cache.
  56. */
  57. function unloadRequireCache(matcher) {
  58. /* istanbul ignore else: impossible to test */
  59. if (matcher && typeof require !== 'undefined' && require && require.cache) {
  60. Object.keys(require.cache).forEach(filename => {
  61. if (matcher(filename)) {
  62. delete require.cache[filename];
  63. }
  64. });
  65. }
  66. }
  67. /**
  68. * hooks `require` to return transformed code to the node module loader.
  69. * Exceptions in the transform result in the original code being used instead.
  70. * @method hookRequire
  71. * @static
  72. * @param matcher {Function(filePath)} a function that is called with the absolute path to the file being
  73. * `require`-d. Should return a truthy value when transformations need to be applied to the code, a falsy value otherwise
  74. * @param transformer {Function(code, filePath)} a function called with the original code and the associated path of the file
  75. * from where the code was loaded. Should return the transformed code.
  76. * @param options {Object} options Optional.
  77. * @param {Boolean} [options.verbose] write a line to standard error every time the transformer is called
  78. * @param {Function} [options.postLoadHook] a function that is called with the name of the file being
  79. * required. This is called after the require is processed irrespective of whether it was transformed.
  80. * @returns {Function} a reset function that can be called to remove the hook
  81. */
  82. function hookRequire(matcher, transformer, options) {
  83. options = options || {};
  84. let disable = false;
  85. const fn = transformFn(matcher, transformer, options.verbose);
  86. const postLoadHook =
  87. options.postLoadHook && typeof options.postLoadHook === 'function'
  88. ? options.postLoadHook
  89. : null;
  90. const extensions = options.extensions || ['.js'];
  91. extensions.forEach(ext => {
  92. appendTransform((code, filename) => {
  93. if (disable) {
  94. return code;
  95. }
  96. const ret = fn(code, filename);
  97. if (postLoadHook) {
  98. postLoadHook(filename);
  99. }
  100. return ret.code;
  101. }, ext);
  102. });
  103. return function() {
  104. disable = true;
  105. };
  106. }
  107. /**
  108. * hooks `vm.createScript` to return transformed code out of which a `Script` object will be created.
  109. * Exceptions in the transform result in the original code being used instead.
  110. * @method hookCreateScript
  111. * @static
  112. * @param matcher {Function(filePath)} a function that is called with the filename passed to `vm.createScript`
  113. * Should return a truthy value when transformations need to be applied to the code, a falsy value otherwise
  114. * @param transformer {Function(code, filePath)} a function called with the original code and the filename passed to
  115. * `vm.createScript`. Should return the transformed code.
  116. * @param options {Object} options Optional.
  117. * @param {Boolean} [options.verbose] write a line to standard error every time the transformer is called
  118. */
  119. function hookCreateScript(matcher, transformer, opts) {
  120. opts = opts || {};
  121. const fn = transformFn(matcher, transformer, opts.verbose);
  122. vm.createScript = function(code, file) {
  123. const ret = fn(code, file);
  124. return originalCreateScript(ret.code, file);
  125. };
  126. }
  127. /**
  128. * unhooks vm.createScript, restoring it to its original state.
  129. * @method unhookCreateScript
  130. * @static
  131. */
  132. function unhookCreateScript() {
  133. vm.createScript = originalCreateScript;
  134. }
  135. /**
  136. * hooks `vm.runInThisContext` to return transformed code.
  137. * @method hookRunInThisContext
  138. * @static
  139. * @param matcher {Function(filePath)} a function that is called with the filename passed to `vm.runInThisContext`
  140. * Should return a truthy value when transformations need to be applied to the code, a falsy value otherwise
  141. * @param transformer {Function(code, options)} a function called with the original code and the filename passed to
  142. * `vm.runInThisContext`. Should return the transformed code.
  143. * @param opts {Object} [opts={}] options
  144. * @param {Boolean} [opts.verbose] write a line to standard error every time the transformer is called
  145. */
  146. function hookRunInThisContext(matcher, transformer, opts) {
  147. opts = opts || {};
  148. const fn = transformFn(matcher, transformer, opts.verbose);
  149. vm.runInThisContext = function(code, options) {
  150. const ret = fn(code, options);
  151. return originalRunInThisContext(ret.code, options);
  152. };
  153. }
  154. /**
  155. * unhooks vm.runInThisContext, restoring it to its original state.
  156. * @method unhookRunInThisContext
  157. * @static
  158. */
  159. function unhookRunInThisContext() {
  160. vm.runInThisContext = originalRunInThisContext;
  161. }
  162. /**
  163. * hooks `vm.runInContext` to return transformed code.
  164. * @method hookRunInContext
  165. * @static
  166. * @param matcher {Function(filePath)} a function that is called with the filename passed to `vm.createScript`
  167. * Should return a truthy value when transformations need to be applied to the code, a falsy value otherwise
  168. * @param transformer {Function(code, filePath)} a function called with the original code and the filename passed to
  169. * `vm.createScript`. Should return the transformed code.
  170. * @param opts {Object} [opts={}] options
  171. * @param {Boolean} [options.verbose] write a line to standard error every time the transformer is called
  172. */
  173. function hookRunInContext(matcher, transformer, opts) {
  174. opts = opts || {};
  175. const fn = transformFn(matcher, transformer, opts.verbose);
  176. vm.runInContext = function(code, context, file) {
  177. const ret = fn(code, file);
  178. const coverageVariable = opts.coverageVariable || '__coverage__';
  179. // Refer coverage variable in context to global coverage variable.
  180. // So that coverage data will be written in global coverage variable for unit tests run in vm.runInContext.
  181. // If all unit tests are run in vm.runInContext, no global coverage variable will be generated.
  182. // Thus initialize a global coverage variable here.
  183. if (!global[coverageVariable]) {
  184. global[coverageVariable] = {};
  185. }
  186. context[coverageVariable] = global[coverageVariable];
  187. return originalRunInContext(ret.code, context, file);
  188. };
  189. }
  190. /**
  191. * unhooks vm.runInContext, restoring it to its original state.
  192. * @method unhookRunInContext
  193. * @static
  194. */
  195. function unhookRunInContext() {
  196. vm.runInContext = originalRunInContext;
  197. }
  198. /**
  199. * istanbul-lib-hook provides mechanisms to transform code in the scope of `require`,
  200. * `vm.createScript`, `vm.runInThisContext` etc.
  201. *
  202. * This mechanism is general and relies on a user-supplied `matcher` function that
  203. * determines when transformations should be performed and a user-supplied `transformer`
  204. * function that performs the actual transform. Instrumenting code for coverage is
  205. * one specific example of useful hooking.
  206. *
  207. * Note that both the `matcher` and `transformer` must execute synchronously.
  208. *
  209. * @module Exports
  210. * @example
  211. * var hook = require('istanbul-lib-hook'),
  212. * myMatcher = function (file) { return file.match(/foo/); },
  213. * myTransformer = function (code, file) {
  214. * return 'console.log("' + file + '");' + code;
  215. * };
  216. *
  217. * hook.hookRequire(myMatcher, myTransformer);
  218. * var foo = require('foo'); //will now print foo's module path to console
  219. */
  220. module.exports = {
  221. hookRequire,
  222. hookCreateScript,
  223. unhookCreateScript,
  224. hookRunInThisContext,
  225. unhookRunInThisContext,
  226. hookRunInContext,
  227. unhookRunInContext,
  228. unloadRequireCache
  229. };