import { GLOBAL_CLI_PLUGIN_CONFIG_DEFAULT_CONTENT, GLOBAL_CLI_PLUGIN_CONFIG_FILE_PATH, LOCAL_CONFIG_DEFAULT_CONTENT, } from '@ones-open/cli-utils' import { getYamlConfigContent, PluginType, updateYamlConfigContent } from '@ones-open/cli-utils' import type { ProjectPluginConfig } from '@ones-open/cli-utils' import { isString, lowerCase, merge } from '@senojs/lodash' import fse from 'fs-extra' import { customAlphabet, nanoid } from 'nanoid' const { ensureFile } = fse const PLUGIN_TYPE_ARRAY_MAP = Object.entries(PluginType) .filter(([, value]) => !isString(value)) .map(([key, value]) => { return [lowerCase(key), value] }) as [string, PluginType][] const PLUGIN_TYPE_MAP = new Map(PLUGIN_TYPE_ARRAY_MAP) function checkIsLegalPluginType( pluginType?: string, ): pluginType is Lowercase { if (!pluginType) return false return PLUGIN_TYPE_MAP.has(pluginType) } function getPluginTypeValue(pluginType?: string) { if (!pluginType) return undefined return PLUGIN_TYPE_MAP.get(pluginType) } async function initGlobalPluginConfig() { try { await ensureFile(GLOBAL_CLI_PLUGIN_CONFIG_FILE_PATH) } catch (error) { // File and folders now has been created // Then we can safely write the file // About ensureFile method you can learn more from: // https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureFile.md } finally { await updateYamlConfigContent( GLOBAL_CLI_PLUGIN_CONFIG_FILE_PATH, GLOBAL_CLI_PLUGIN_CONFIG_DEFAULT_CONTENT, ) } } interface InitPluginYamlPrams { name: string description: string pluginType?: string policy: string appID: string } async function initPluginYaml( configPath: string, { name, description, pluginType, policy, appID }: InitPluginYamlPrams, ) { const rawPluginConfig = await getYamlConfigContent(configPath) const pluginId = appID || nanoid(8) const pluginConfig = merge(rawPluginConfig, { service: { name, description, app_id: pluginId, scope: (pluginType && getPluginTypeValue(pluginType)) || PluginType.Team, policy: { policy, target: '', }, }, modules: [], }) await updateYamlConfigContent(configPath, pluginConfig) } async function initProjectLocalYaml(configPath: string) { const localIdGenerator = customAlphabet('1234567890', 10) const id = localIdGenerator() const defaultLocalConfig = merge({ ...LOCAL_CONFIG_DEFAULT_CONTENT }, { local: { id } }) await updateYamlConfigContent(configPath, defaultLocalConfig) } export { checkIsLegalPluginType, getPluginTypeValue, initGlobalPluginConfig, initPluginYaml, initProjectLocalYaml, }