@gramio/autoload
Version:
Autoload commands plugin for GramIO
49 lines (45 loc) • 1.97 kB
JavaScript
import path from 'node:path';
import url from 'node:url';
import { fdir } from 'fdir';
import { Plugin } from 'gramio';
import process from 'node:process';
function getPath(dir) {
if (path.isAbsolute(dir)) return dir;
if (path.isAbsolute(process.argv[1]))
return path.join(process.argv[1], "..", dir);
return path.join(process.cwd(), process.argv[1], "..", dir);
}
async function autoload(options) {
const failGlob = options?.failGlob ?? true;
const patterns = typeof options?.patterns === "string" ? [options?.patterns] : options?.patterns ?? ["**/*.{ts,js,cjs,mjs}"];
const pathToAutoload = options?.path ?? "./commands";
const directoryPath = getPath(pathToAutoload);
const getImportName = options?.import ?? "default";
const plugin = new Plugin("@gramio/autoload");
const paths = await new fdir(options?.fdir || {}).withRelativePaths().globWithOptions(patterns, options?.picomatch || {}).crawl(directoryPath).withPromise();
if (failGlob && paths.length === 0)
throw new Error(
`No matches found in ${directoryPath}. You can disable this error by setting the failGlob parameter to false in the options of autoload plugin`
);
for await (const filePath of paths) {
const absolute = String(
url.pathToFileURL(path.join(directoryPath, filePath))
);
if (options?.onLoad) options.onLoad({ absolute, relative: filePath });
const file = await import(absolute);
const importName = typeof getImportName === "string" ? getImportName : getImportName(file);
if (!file[importName] && options?.skipImportErrors) continue;
if (!file[importName])
throw new Error(`${filePath} don't provide export ${importName}`);
plugin.group(file[importName]);
}
if (options?.onFinish)
options.onFinish(
paths.map((filePath) => ({
absolute: String(url.pathToFileURL(path.join(directoryPath, filePath))),
relative: filePath
}))
);
return plugin;
}
export { autoload };