]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/yarn.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / lib / plugins / yarn.ts
1 import { outputJSON, pathExists } from 'fs-extra'
2 import { join } from 'path'
3 import { execShell } from '../../helpers/core-utils'
4 import { isNpmPluginNameValid, isPluginStableOrUnstableVersionValid } from '../../helpers/custom-validators/plugins'
5 import { logger } from '../../helpers/logger'
6 import { CONFIG } from '../../initializers/config'
7 import { getLatestPluginVersion } from './plugin-index'
8
9 async function installNpmPlugin (npmName: string, versionArg?: string) {
10 // Security check
11 checkNpmPluginNameOrThrow(npmName)
12 if (versionArg) checkPluginVersionOrThrow(versionArg)
13
14 const version = versionArg || await getLatestPluginVersion(npmName)
15
16 let toInstall = npmName
17 if (version) toInstall += `@${version}`
18
19 const { stdout } = await execYarn('add ' + toInstall)
20
21 logger.debug('Added a yarn package.', { yarnStdout: stdout })
22 }
23
24 async function installNpmPluginFromDisk (path: string) {
25 await execYarn('add file:' + path)
26 }
27
28 async function removeNpmPlugin (name: string) {
29 checkNpmPluginNameOrThrow(name)
30
31 await execYarn('remove ' + name)
32 }
33
34 async function rebuildNativePlugins () {
35 await execYarn('install --pure-lockfile')
36 }
37
38 // ############################################################################
39
40 export {
41 installNpmPlugin,
42 installNpmPluginFromDisk,
43 rebuildNativePlugins,
44 removeNpmPlugin
45 }
46
47 // ############################################################################
48
49 async function execYarn (command: string) {
50 try {
51 const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
52 const pluginPackageJSON = join(pluginDirectory, 'package.json')
53
54 // Create empty package.json file if needed
55 if (!await pathExists(pluginPackageJSON)) {
56 await outputJSON(pluginPackageJSON, {})
57 }
58
59 return execShell(`yarn ${command}`, { cwd: pluginDirectory })
60 } catch (result) {
61 logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
62
63 throw result.err
64 }
65 }
66
67 function checkNpmPluginNameOrThrow (name: string) {
68 if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
69 }
70
71 function checkPluginVersionOrThrow (name: string) {
72 if (!isPluginStableOrUnstableVersionValid(name)) throw new Error('Invalid NPM plugin version to install')
73 }