UNPKG

@allgemein/moduls

Version:

Commons-moduls handles and manages contextual moduls for complex and modular applications.

90 lines 3.58 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RequireLoader = void 0; const path = require("path"); const lodash_1 = require("lodash"); const RequireHandle_1 = require("./RequireHandle"); const AbstractModuleLoader_1 = require("../AbstractModuleLoader"); const Helper_1 = require("../../utils/Helper"); class RequireLoader extends AbstractModuleLoader_1.AbstractModuleLoader { async loadOne(modul) { let handle = new RequireHandle_1.RequireHandle(modul); // necassary to extend the search directories of require let _module = this.registry.options().module; let new_node_modules_dir = path.dirname(modul.path); //split.join(path.sep); if (_module['paths'].indexOf(new_node_modules_dir) == -1) { _module['paths'].unshift(new_node_modules_dir); } if (modul.internal) { handle.ref = _module.require(modul.name); } else { handle.ref = _module.require(modul.getMain()); } if (handle.ref.exposesHooks) { handle.exposesHooks = handle.ref.exposesHooks; } Object.getOwnPropertyNames(handle.ref).forEach(function (val, idx, array) { if (handle.ref[val] && (0, lodash_1.isFunction)(handle.ref[val]) && val != 'exposesHooks' && val.match(/^on[A-Z]/)) { let _val = val.replace('on', ''); _val = _val[0].toLowerCase() + _val.substring(1); handle.usesHooks.push(_val); } }); return handle; } async invokeHook(hook, ...args) { let options = { concurrency: Infinity }; if ((0, lodash_1.isObject)(hook)) { options = hook; hook = options.hook; } let handles = (0, lodash_1.filter)(this._handles, function (_x) { return _x.usesHooks.indexOf(hook) > -1; }); return await Promise.all((0, lodash_1.map)(handles, (handle) => { let _args = [handle, hook]; _args = _args.concat(args); return RequireLoader.handleCall.apply(null, _args); })); } static async handleCall(handle, hook, ...args) { let hookCall = 'on' + Helper_1.Helper.ucfirst(hook); if (handle.usesHooks.indexOf(hook) > -1) { return new Promise(function (res, rej) { if (handle.ref[hookCall].length == args.length) { let result, err; try { result = handle.ref[hookCall].apply(handle.ref, args); } catch (_err) { err = _err; rej(err); } if (!err) { res(result); } } else if (handle.ref[hookCall].length == (args.length + 1)) { args.push(function (err, result) { if (err) { rej(err); } else { res(result); } }); handle.ref[hookCall].apply(handle.ref, args); } else { rej(new Error('wrong defined function ' + hook + ' ' + hookCall + ' ' + handle.module.name)); } }); } else { return null; } } } exports.RequireLoader = RequireLoader; //# sourceMappingURL=RequireLoader.js.map