hook.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.makeHook = void 0;
  7. var vm_1 = __importDefault(require("vm"));
  8. exports.makeHook = function (cfg, wrapper, callback) {
  9. // Hook into Node's `require(...)`
  10. updateHooks();
  11. // Patch the vm module to watch files executed via one of these methods:
  12. if (cfg.vm) {
  13. patch(vm_1.default, 'createScript', 1);
  14. patch(vm_1.default, 'runInThisContext', 1);
  15. patch(vm_1.default, 'runInNewContext', 2);
  16. patch(vm_1.default, 'runInContext', 2);
  17. }
  18. /**
  19. * Patch the specified method to watch the file at the given argument
  20. * index.
  21. */
  22. function patch(obj, method, optionsArgIndex) {
  23. var orig = obj[method];
  24. if (!orig)
  25. return;
  26. obj[method] = function () {
  27. var opts = arguments[optionsArgIndex];
  28. var file = null;
  29. if (opts) {
  30. file = typeof opts == 'string' ? opts : opts.filename;
  31. }
  32. if (file)
  33. callback(file);
  34. return orig.apply(this, arguments);
  35. };
  36. }
  37. /**
  38. * (Re-)install hooks for all registered file extensions.
  39. */
  40. function updateHooks() {
  41. Object.keys(require.extensions).forEach(function (ext) {
  42. var fn = require.extensions[ext];
  43. if (typeof fn === 'function' && fn.name !== 'nodeDevHook') {
  44. require.extensions[ext] = createHook(fn);
  45. }
  46. });
  47. }
  48. /**
  49. * Returns a function that can be put into `require.extensions` in order to
  50. * invoke the callback when a module is required for the first time.
  51. */
  52. function createHook(handler) {
  53. return function nodeDevHook(module, filename) {
  54. if (module.parent === wrapper) {
  55. // If the main module is required conceal the wrapper
  56. module.id = '.';
  57. module.parent = null;
  58. process.mainModule = module;
  59. }
  60. if (!module.loaded)
  61. callback(module.filename);
  62. // Invoke the original handler
  63. handler(module, filename);
  64. // Make sure the module did not hijack the handler
  65. updateHooks();
  66. };
  67. }
  68. };