UNPKG

@sprucelabs/spruce-skill-utils

Version:

Loosely coupled classes and functions to make skill development faster! 🏎

83 lines (82 loc) 2.49 kB
import pathUtil from 'path'; import fs from 'fs-extra'; import get from 'lodash/get.js'; import set from 'lodash/set.js'; import SpruceError from '../errors/SpruceError.js'; import diskUtil from '../utilities/disk.utility.js'; export default class PkgService { constructor(cwd) { this.cwd = cwd; } get(path) { const contents = this.readPackage(); return get(contents, path); } set(options) { const { path, value } = options; const contents = this.readPackage(); const updated = set(contents, path, value); const destination = this.buildPath(); fs.outputFileSync(destination, JSON.stringify(updated, null, 2) + '\n'); this._parsedPkg = undefined; } doesExist() { return diskUtil.doesFileExist(this.buildPath()); } unset(path) { this.set({ path, value: undefined }); } readPackage() { if (this._parsedPkg) { return this._parsedPkg; } const packagePath = this.buildPath(); try { const contents = fs.readFileSync(packagePath).toString(); const parsed = JSON.parse(contents); this._parsedPkg = parsed; return parsed; } catch (err) { throw new SpruceError({ code: 'INVALID_PACKAGE_JSON', path: packagePath, originalError: err, errorMessage: err.message, }); } } buildPath() { return pathUtil.join(this.cwd, 'package.json'); } isInstalled(pkg) { var _a, _b; try { const contents = this.readPackage(); return (!!((_a = contents.dependencies) === null || _a === void 0 ? void 0 : _a[pkg]) || !!((_b = contents.devDependencies) === null || _b === void 0 ? void 0 : _b[pkg])); } catch (e) { return false; } } deleteLockFile() { const files = ['package-lock.json', 'yarn.lock']; for (const file of files) { const lock = pathUtil.join(this.cwd, file); if (diskUtil.doesFileExist(lock)) { diskUtil.deleteFile(lock); } } } stripLatest(name) { return name.replace('@latest', ''); } buildPackageName(dep) { const { name, version } = dep; if (!version) { return name; } return `${name}@${version}`; } }