From 23a323c675c786055d142945775d02bb7e257825 Mon Sep 17 00:00:00 2001 From: Joakim Carlstein Date: Wed, 15 Nov 2023 16:02:57 +0100 Subject: [PATCH] feat(plugin-tools): add convenience functions getOrLoadPlugin and getOrLoadPlugins --- .changeset/eight-baboons-press.md | 5 +++ packages/plugin-tools/src/index.ts | 49 +++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 .changeset/eight-baboons-press.md diff --git a/.changeset/eight-baboons-press.md b/.changeset/eight-baboons-press.md new file mode 100644 index 0000000..cbae31a --- /dev/null +++ b/.changeset/eight-baboons-press.md @@ -0,0 +1,5 @@ +--- +'@emigrate/plugin-tools': minor +--- + +Add the convenience functions `getOrLoadPlugin` and `getOrLoadPlugins` diff --git a/packages/plugin-tools/src/index.ts b/packages/plugin-tools/src/index.ts index a96e8ac..caae636 100644 --- a/packages/plugin-tools/src/index.ts +++ b/packages/plugin-tools/src/index.ts @@ -1,5 +1,11 @@ import process from 'node:process'; -import { type PluginFromType, type PluginType, type GeneratorPlugin, type StoragePlugin } from './types.js'; +import { + type PluginFromType, + type PluginType, + type GeneratorPlugin, + type StoragePlugin, + type Plugin, +} from './types.js'; export const isGeneratorPlugin = (plugin: any): plugin is GeneratorPlugin => { if (!plugin || typeof plugin !== 'object') { @@ -29,6 +35,47 @@ export const isPluginOfType = (type: T, plugin: any): plug throw new Error(`Unknown plugin type: ${type}`); }; +export const getOrLoadPlugin = async ( + type: T, + plugins: Array, +): Promise | undefined> => { + for await (const plugin of plugins) { + if (isPluginOfType(type, plugin)) { + return plugin; + } + + const loadedPlugin = typeof plugin === 'string' ? await loadPlugin(type, plugin) : undefined; + + if (loadedPlugin) { + return loadedPlugin; + } + } + + return undefined; +}; + +export const getOrLoadPlugins = async ( + type: T, + plugins: Array, +): Promise>> => { + const result: Array> = []; + + for await (const plugin of plugins) { + if (isPluginOfType(type, plugin)) { + result.push(plugin); + continue; + } + + const loadedPlugin = typeof plugin === 'string' ? await loadPlugin(type, plugin) : undefined; + + if (loadedPlugin) { + result.push(loadedPlugin); + } + } + + return result; +}; + export const loadPlugin = async ( type: T, plugin: string,