UNPKG

unwire

Version:

Dependency injection with 'require()'

69 lines 2.28 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const resolve_1 = __importDefault(require("resolve")); const I = (x) => x; const ORIGINAL = Symbol('Original'); const resolveModulePath = (modulePath, context) => { if (resolve_1.default.isCore(modulePath)) { return modulePath; } const folder = path_1.default.dirname(context); const resolvedPath = resolve_1.default.sync(modulePath, { basedir: folder, extensions: ['.js', '.ts'] }); return fs_1.default.realpathSync(resolvedPath); }; exports.resolveModulePath = resolveModulePath; const replace = (modulePath, context, value) => { const fullPath = resolveModulePath(modulePath, context); // Overwrite the require cache require.cache[fullPath] = { exports: value, }; return value; }; exports.replace = replace; const mock = (modulePath, context, mock = I) => { const fullPath = resolveModulePath(modulePath, context); const cache = require.cache[fullPath]; // Check if we have already rewired this path let original; if (typeof cache !== 'undefined' && Object.hasOwnProperty.call(cache, ORIGINAL)) { original = cache[ORIGINAL]; } else { original = require(fullPath); } // Mock the module const mockedModule = mock(original); // Overwrite the require cache require.cache[fullPath] = { exports: mockedModule, [ORIGINAL]: original, }; return mockedModule; }; exports.mock = mock; // Remove a module from the require cache const flush = (modulePath, context) => { const fullPath = resolveModulePath(modulePath, context); return delete require.cache[fullPath]; }; exports.flush = flush; // Completely clear the require cache const flushAllModules = () => { for (const key in require.cache) { if (Object.hasOwnProperty.call(require.cache, key)) { delete require.cache[key]; } } }; exports.flushAllModules = flushAllModules; //# sourceMappingURL=core.js.map