core/src/plugin/loader.ts

75 lines
1.8 KiB
TypeScript

import * as fs from 'fs-extra';
import * as path from 'path';
import { IEnvironment } from '../types/environment';
import { IPluginManifest } from './plugin';
export class PluginMetaLoader {
constructor(private env: IEnvironment) {}
public async load(name: string): Promise<IPluginManifest> {
if (name === 'squeebot') {
throw new Error('Illegal name.');
}
const fullpath = path.join(this.env.pluginsPath, name);
const metapath = path.join(fullpath, 'plugin.json');
if (!await fs.pathExists(metapath)) {
throw new Error('Not a plugin directory.');
}
// Read the metadata
const json = await fs.readJson(metapath);
// Mandatory fields
if (!json.name) {
throw new Error('Plugin metadata does not specify a name, for some reason');
}
if (json.name === 'squeebot') {
throw new Error('Illegal name.');
}
if (!json.version) {
throw new Error('Plugin metadata does not specify a version, for some reason');
}
// Ensure main file exists
if (!json.main) {
json.main = 'plugin.js';
}
const mainfile = path.resolve(fullpath, json.main);
if (!await fs.pathExists(mainfile)) {
throw new Error('Plugin does not have a main file or it is misconfigured.');
}
json.fullPath = fullpath;
json.main = mainfile;
if (!json.dependencies) {
json.dependencies = [];
}
if (!json.npmDependencies) {
json.npmDependencies = [];
}
return json;
}
public async loadAll(): Promise<IPluginManifest[]> {
const dirlist = await fs.readdir(this.env.pluginsPath);
const plugins: IPluginManifest[] = [];
for (const file of dirlist) {
try {
const plugin = await this.load(path.basename(file));
plugins.push(plugin);
} catch (e) {
console.error(e);
}
}
return plugins;
}
}