patch-require.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const Module = require('node:module')
  2. /**
  3. * @param {Record<string, any>} mods
  4. */
  5. module.exports.patchRequire = function patchRequire(mods, parentCache) {
  6. function wrapRequire(origRequire) {
  7. return Object.assign(
  8. function (id) {
  9. // Patch require(…) to return the cached module
  10. if (mods.hasOwnProperty(id)) {
  11. return mods[id]
  12. }
  13. return origRequire.apply(this, arguments)
  14. },
  15. // Make sure we carry over other properties of the original require(…)
  16. origRequire,
  17. {
  18. resolve(id) {
  19. // Defer to the "parent" require cache when resolving the module
  20. // This also requires that the module be provided as a "native module" to JITI
  21. // The path returned here is VERY important as it ensures that the `isNativeRe` in JITI
  22. // passes which is required for the module to be loaded via the native require(…) function
  23. // Thankfully, the regex just means that it needs to be in a node_modules folder which is true
  24. // even when bundled using Vercel's `pkg`
  25. if (parentCache.hasOwnProperty(id)) {
  26. return parentCache[id].filename
  27. }
  28. return origRequire.resolve.apply(this, arguments)
  29. },
  30. }
  31. )
  32. }
  33. let origRequire = Module.prototype.require
  34. let origCreateRequire = Module.createRequire
  35. // We have to augment the default "require" in every module
  36. Module.prototype.require = wrapRequire(origRequire)
  37. // And any "require" created by the "createRequire" method
  38. Module.createRequire = function () {
  39. return wrapRequire(origCreateRequire.apply(this, arguments))
  40. }
  41. }