index.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. 'use strict';
  2. /* (c) 2015 Ari Porad (@ariporad) <http://ariporad.com>. License: ariporad.mit-license.org */
  3. const BuiltinModule = require('module');
  4. const path = require('path');
  5. const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;
  6. // Guard against poorly-mocked module constructors.
  7. const Module =
  8. module.constructor.length > 1 ? module.constructor : BuiltinModule;
  9. const HOOK_RETURNED_NOTHING_ERROR_MESSAGE =
  10. '[Pirates] A hook returned a non-string, or nothing at all! This is a' +
  11. ' violation of intergalactic law!\n' +
  12. '--------------------\n' +
  13. 'If you have no idea what this means or what Pirates is, let me explain: ' +
  14. 'Pirates is a module that makes it easy to implement require hooks. One of' +
  15. " the require hooks you're using uses it. One of these require hooks" +
  16. " didn't return anything from it's handler, so we don't know what to" +
  17. ' do. You might want to debug this.';
  18. /**
  19. * @param {string} filename The filename to check.
  20. * @param {string[]} exts The extensions to hook. Should start with '.' (ex. ['.js']).
  21. * @param {Matcher|null} matcher A matcher function, will be called with path to a file. Should return truthy if the file should be hooked, falsy otherwise.
  22. * @param {boolean} ignoreNodeModules Auto-ignore node_modules. Independent of any matcher.
  23. */
  24. function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
  25. if (typeof filename !== 'string') {
  26. return false;
  27. }
  28. if (exts.indexOf(path.extname(filename)) === -1) {
  29. return false;
  30. }
  31. const resolvedFilename = path.resolve(filename);
  32. if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) {
  33. return false;
  34. }
  35. if (matcher && typeof matcher === 'function') {
  36. return !!matcher(resolvedFilename);
  37. }
  38. return true;
  39. }
  40. /**
  41. * @callback Hook The hook. Accepts the code of the module and the filename.
  42. * @param {string} code
  43. * @param {string} filename
  44. * @returns {string}
  45. */
  46. /**
  47. * @callback Matcher A matcher function, will be called with path to a file.
  48. *
  49. * Should return truthy if the file should be hooked, falsy otherwise.
  50. * @param {string} path
  51. * @returns {boolean}
  52. */
  53. /**
  54. * @callback RevertFunction Reverts the hook when called.
  55. * @returns {void}
  56. */
  57. /**
  58. * @typedef {object} Options
  59. * @property {Matcher|null} [matcher=null] A matcher function, will be called with path to a file.
  60. *
  61. * Should return truthy if the file should be hooked, falsy otherwise.
  62. *
  63. * @property {string[]} [extensions=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  64. * @property {string[]} [exts=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  65. *
  66. * @property {string[]} [extension=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  67. * @property {string[]} [ext=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  68. *
  69. * @property {boolean} [ignoreNodeModules=true] Auto-ignore node_modules. Independent of any matcher.
  70. */
  71. /**
  72. * Add a require hook.
  73. *
  74. * @param {Hook} hook The hook. Accepts the code of the module and the filename. Required.
  75. * @param {Options} [opts] Options
  76. * @returns {RevertFunction} The `revert` function. Reverts the hook when called.
  77. */
  78. function addHook(hook, opts = {}) {
  79. let reverted = false;
  80. const loaders = [];
  81. const oldLoaders = [];
  82. let exts;
  83. // We need to do this to fix #15. Basically, if you use a non-standard extension (ie. .jsx), then
  84. // We modify the .js loader, then use the modified .js loader for as the base for .jsx.
  85. // This prevents that.
  86. const originalJSLoader = Module._extensions['.js'];
  87. const matcher = opts.matcher || null;
  88. const ignoreNodeModules = opts.ignoreNodeModules !== false;
  89. exts = opts.extensions || opts.exts || opts.extension || opts.ext || ['.js'];
  90. if (!Array.isArray(exts)) {
  91. exts = [exts];
  92. }
  93. exts.forEach((ext) => {
  94. if (typeof ext !== 'string') {
  95. throw new TypeError(`Invalid Extension: ${ext}`);
  96. }
  97. const oldLoader = Module._extensions[ext] || originalJSLoader;
  98. oldLoaders[ext] = Module._extensions[ext];
  99. loaders[ext] = Module._extensions[ext] = function newLoader(mod, filename) {
  100. let compile;
  101. if (!reverted) {
  102. if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
  103. compile = mod._compile;
  104. mod._compile = function _compile(code) {
  105. // reset the compile immediately as otherwise we end up having the
  106. // compile function being changed even though this loader might be reverted
  107. // Not reverting it here leads to long useless compile chains when doing
  108. // addHook -> revert -> addHook -> revert -> ...
  109. // The compile function is also anyway created new when the loader is called a second time.
  110. mod._compile = compile;
  111. const newCode = hook(code, filename);
  112. if (typeof newCode !== 'string') {
  113. throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
  114. }
  115. return mod._compile(newCode, filename);
  116. };
  117. }
  118. }
  119. oldLoader(mod, filename);
  120. };
  121. });
  122. return function revert() {
  123. if (reverted) return;
  124. reverted = true;
  125. exts.forEach((ext) => {
  126. // if the current loader for the extension is our loader then unregister it and set the oldLoader again
  127. // if not we cannot do anything as we cannot remove a loader from within the loader-chain
  128. if (Module._extensions[ext] === loaders[ext]) {
  129. if (!oldLoaders[ext]) {
  130. delete Module._extensions[ext];
  131. } else {
  132. Module._extensions[ext] = oldLoaders[ext];
  133. }
  134. }
  135. });
  136. };
  137. }
  138. exports.addHook = addHook;