1 import { execShell } from '../../helpers/core-utils'
2 import { logger } from '../../helpers/logger'
3 import { isNpmPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins'
4 import { CONFIG } from '../../initializers/config'
5 import { outputJSON, pathExists } from 'fs-extra'
6 import { join } from 'path'
8 async function installNpmPlugin (name: string, version: string) {
10 checkNpmPluginNameOrThrow(name)
11 checkPluginVersionOrThrow(version)
13 const toInstall = `${name}@${version}`
14 await execYarn('add ' + toInstall)
17 async function installNpmPluginFromDisk (path: string) {
18 await execYarn('add file:' + path)
21 async function removeNpmPlugin (name: string) {
22 checkNpmPluginNameOrThrow(name)
24 await execYarn('remove ' + name)
27 // ############################################################################
31 installNpmPluginFromDisk,
35 // ############################################################################
37 async function execYarn (command: string) {
39 const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
40 const pluginPackageJSON = join(pluginDirectory, 'package.json')
42 // Create empty package.json file if needed
43 if (!await pathExists(pluginPackageJSON)) {
44 await outputJSON(pluginPackageJSON, {})
47 await execShell(`yarn ${command}`, { cwd: pluginDirectory })
49 logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
55 function checkNpmPluginNameOrThrow (name: string) {
56 if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
59 function checkPluginVersionOrThrow (name: string) {
60 if (!isPluginVersionValid(name)) throw new Error('Invalid NPM plugin version to install')