All files / lib plugins.js

100% Statements 98/98
100% Branches 37/37
100% Functions 18/18
100% Lines 88/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234              2x 2x 2x   2x 2x 2x   2x 2x   2x 2x                       2x 144x 2x 2x 2x 2x     144x   144x 8x               2x 4x   3x   3x 3x   3x 21x 5x   574x   572x   2x       2x       3x 3x               2x 5x   3x     1x 1x   1x 2x       2x     1x 2x               2x 3x   3x 2x 2x 1x   1x       3x                 2x 141x 141x 3x 3x   141x             2x             2x 2x   2x 1x 1x     1x                         2x 2x   2x 1x 1x     1x                       2x 147x   147x 143x 4x 2x   3x   147x             2x 6x   6x 4x 4x 3x       6x 3x     6x     2x                
"use strict";
/**
 * Plugins.
 *
 * @module 
 */
 
const fs = require("fs");
const path = require("path");
const util = require("util");
 
const _ = require("lodash");
const expect = require("chai").expect;
const U = require("glace-utils");
 
const CONF = U.config; // HACK to avoid cross-import between config.js and plugins.js
const LOG = U.logger;
 
let systemPlugins = null;
let customPlugins = [];
 
/**
 * Get list of found and registered plugins. Each plugin is an object with keys:
 * `name` - plugin name, `path` - plugin path, `module` - loaded plugin module.
 * Order of resolving, if there plugins with the same names:
 * 1. Registered custom plugins.
 * 2. Plugins which are far from `glace-core` package.
 *
 * @function
 * @return {array<object>}
 */
const get = () => {
    if (!systemPlugins) {
        systemPlugins = [];
        systemPlugins = findPlugins(systemPlugins);
        systemPlugins = getPluginsFromDir(systemPlugins);
        systemPlugins = loadPlugins(systemPlugins);
    }
 
    const customPluginNames = getNames({ type: "custom" });
 
    return systemPlugins
        .filter(p => !customPluginNames.includes(p.name))
        .concat(customPlugins);
};
 
/**
 * Traverse folders and find `glace` plugins.
 * @ignore
 */
const findPlugins = plugins => {
    if (CONF.plugins.disableDefault) return plugins;
    
    const SKIPPED_PACKAGES = ["glace-js", "glace-core", "glace-utils"];
 
    const foundPlugins = [];
    const foundPluginNames = [];
 
    for (const pluginDir of dirsToSearchPlugins()) {
        if (!fs.existsSync(pluginDir)) continue;
        for (const fileName of fs.readdirSync(pluginDir)) {
 
            if (!fileName.startsWith("glace-") ||
                SKIPPED_PACKAGES.includes(fileName) ||
                foundPluginNames.includes(fileName)) continue;
 
            foundPlugins.push({
                name: fileName,
                path: path.resolve(pluginDir, fileName),
            });
            foundPluginNames.push(fileName);
        }
    }
 
    return plugins
        .filter(p => !foundPluginNames.includes(p.name))
        .concat(foundPlugins);
};
 
/**
 * Get list of plugins for folder specified in config.
 * @ignore
 */
const getPluginsFromDir = plugins => {
    if (!CONF.plugins.dir) return plugins;
 
    expect(fs.existsSync(CONF.plugins.dir) && fs.statSync(CONF.plugins.dir).isDirectory(),
        `Plugins folder '${CONF.plugins.dir}' doesn't exist or isn't a folder`).to.be.true;
 
    const dirPlugins = [];
    const dirPluginNames = [];
 
    for (const fileName of fs.readdirSync(CONF.plugins.dir)) {
        dirPlugins.push({
            name: fileName,
            path: path.resolve(CONF.plugins.dir, fileName),
        });
        dirPluginNames.push(fileName);
    }
 
    return plugins
        .filter(p => !dirPluginNames.includes(p.name))
        .concat(dirPlugins);
};
 
/**
 * Load required plugins and return back list of loaded plugins.
 * @ignore 
 */
const loadPlugins = plugins => {
    const loadedPlugins = [];
 
    for (const plugin of plugins) {
        try {
            plugin.module = require(plugin.path);
            loadedPlugins.push(Object.freeze(plugin));
        } catch (e) {
            LOG.error(util.format(`Can't load plugin '${plugin.path}':`, e));
        }
    }
 
    return loadedPlugins;
};
 
/**
 * Gets modules from plugins.
 *
 * @arg {string} moduleName - Name of module to request from plugins.
 * @return {object[]} - List of modules requested from plugins.
 */
const getModules = moduleName => {
    const modules = [];
    for (const plugin of get()) {
        const mod = plugin.module[moduleName];
        if (mod) modules.push(mod);
    }
    return modules;
};
/**
 * Clear plugins cache.
 *
 * @function
 */
const clearCache = () => systemPlugins = null;
/**
 * Registers custom plugin.
 *
 * @function
 * @arg {string} name - Name of plugin module.
 */
const register = name => {
    const customPluginNames = getNames({ type: "custom" });
 
    if (customPluginNames.includes(name)) {
        LOG.warn(`Plugin '${name}' is registered already`);
        return;
    }
 
    customPlugins.push({
        name: name,
        path: require.resolve(name),
        module: require(name),
    });
};
 
/**
 * Removes custom plugin from list of registered.
 *
 * @function
 * @arg {string} name - Name of registered plugin.
 */
const remove = name => {
    const customPluginNames = getNames({ type: "custom" });
 
    if (!customPluginNames.includes(name)) {
        LOG.warn(`Plugin '${name}' isn't registered yet`);
        return;
    }
 
    customPlugins = customPlugins.filter(p => p.name !== name);
};
 
/**
 * Gets names of plugins.
 *
 * @function
 * @arg {object} opts - Options.
 * @arg {string} [opts.type] - Type of plugins. Supported values are `custom`
 * and `system`, if omitted then names of all plugins will be returned.
 * @return {array<string>} Plugin names.
 */
const getNames = opts => {
    opts = opts || {};
    let names;
    if (opts.type === "custom") {
        names = customPlugins.map(p => p.name).sort();
    } else if (opts.type === "system") {
        names = (systemPlugins || []).map(p => p.name).sort();
    } else {
        names = _.uniq((systemPlugins || []).map(p => p.name).concat(customPlugins.map(p => p.name))).sort();
    };
    return names;
};
 
/**
 * Get folders to search plugins.
 * @ignore
 */
const dirsToSearchPlugins = () => {
    const pluginDirs = _.clone(module.paths);
 
    if (require.main) {
        const mainDir = path.dirname(require.main.filename);
        if (!pluginDirs.includes(mainDir)) {
            pluginDirs.unshift(mainDir);
        }
    }
 
    if (!pluginDirs.includes(U.cwd)) {
        pluginDirs.unshift(U.cwd);
    }
 
    return pluginDirs;
};
 
module.exports = {
    get,
    getModules,
    getNames,
    register,
    remove,
    clearCache,
};