PeerTube/server/core/lib/plugins/yarn.ts

74 lines
2.2 KiB
TypeScript
Raw Normal View History

import { outputJSON, pathExists } from 'fs-extra/esm'
2021-04-12 03:10:48 -05:00
import { join } from 'path'
import { execShell } from '../../helpers/core-utils.js'
import { isNpmPluginNameValid, isPluginStableOrUnstableVersionValid } from '../../helpers/custom-validators/plugins.js'
import { logger } from '../../helpers/logger.js'
import { CONFIG } from '../../initializers/config.js'
import { getLatestPluginVersion } from './plugin-index.js'
2019-07-05 08:28:49 -05:00
2021-04-12 03:10:48 -05:00
async function installNpmPlugin (npmName: string, versionArg?: string) {
2019-07-05 08:28:49 -05:00
// Security check
2019-07-19 03:37:35 -05:00
checkNpmPluginNameOrThrow(npmName)
2021-04-12 03:10:48 -05:00
if (versionArg) checkPluginVersionOrThrow(versionArg)
const version = versionArg || await getLatestPluginVersion(npmName)
2019-07-19 03:37:35 -05:00
let toInstall = npmName
if (version) toInstall += `@${version}`
2019-07-05 08:28:49 -05:00
2019-07-19 07:36:04 -05:00
const { stdout } = await execYarn('add ' + toInstall)
logger.debug('Added a yarn package.', { yarnStdout: stdout })
2019-07-05 08:28:49 -05:00
}
async function installNpmPluginFromDisk (path: string) {
await execYarn('add file:' + path)
}
async function removeNpmPlugin (name: string) {
checkNpmPluginNameOrThrow(name)
await execYarn('remove ' + name)
}
async function rebuildNativePlugins () {
await execYarn('install --pure-lockfile')
}
2019-07-05 08:28:49 -05:00
// ############################################################################
export {
installNpmPlugin,
installNpmPluginFromDisk,
rebuildNativePlugins,
2019-07-05 08:28:49 -05:00
removeNpmPlugin
}
// ############################################################################
async function execYarn (command: string) {
try {
const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
const pluginPackageJSON = join(pluginDirectory, 'package.json')
// Create empty package.json file if needed
if (!await pathExists(pluginPackageJSON)) {
await outputJSON(pluginPackageJSON, {})
}
2019-07-19 07:36:04 -05:00
return execShell(`yarn ${command}`, { cwd: pluginDirectory })
2019-07-05 08:28:49 -05:00
} catch (result) {
logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
throw result.err
}
}
function checkNpmPluginNameOrThrow (name: string) {
if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
}
function checkPluginVersionOrThrow (name: string) {
if (!isPluginStableOrUnstableVersionValid(name)) throw new Error('Invalid NPM plugin version to install')
2019-07-05 08:28:49 -05:00
}