1 import { outputJSON, pathExists } from 'fs-extra'
2 import { join } from 'path'
3 import { execShell } from '../../helpers/core-utils'
4 import { isNpmPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins'
5 import { logger } from '../../helpers/logger'
6 import { CONFIG } from '../../initializers/config'
7 import { getLatestPluginVersion } from './plugin-index'
9 async function installNpmPlugin (npmName: string, versionArg?: string) {
11 checkNpmPluginNameOrThrow(npmName)
12 if (versionArg) checkPluginVersionOrThrow(versionArg)
14 const version = versionArg || await getLatestPluginVersion(npmName)
16 let toInstall = npmName
17 if (version) toInstall += `@${version}`
19 const { stdout } = await execYarn('add ' + toInstall)
21 logger.debug('Added a yarn package.', { yarnStdout: stdout })
24 async function installNpmPluginFromDisk (path: string) {
25 await execYarn('add file:' + path)
28 async function removeNpmPlugin (name: string) {
29 checkNpmPluginNameOrThrow(name)
31 await execYarn('remove ' + name)
34 // ############################################################################
38 installNpmPluginFromDisk,
42 // ############################################################################
44 async function execYarn (command: string) {
46 const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
47 const pluginPackageJSON = join(pluginDirectory, 'package.json')
49 // Create empty package.json file if needed
50 if (!await pathExists(pluginPackageJSON)) {
51 await outputJSON(pluginPackageJSON, {})
54 return execShell(`yarn ${command}`, { cwd: pluginDirectory })
56 logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
62 function checkNpmPluginNameOrThrow (name: string) {
63 if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
66 function checkPluginVersionOrThrow (name: string) {
67 if (!isPluginVersionValid(name)) throw new Error('Invalid NPM plugin version to install')