UNPKG

@sprucelabs/spruce-skill-utils

Version:

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

88 lines (87 loc) 2.87 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const path_1 = __importDefault(require("path")); const fs_extra_1 = __importDefault(require("fs-extra")); const get_1 = __importDefault(require("lodash/get")); const set_1 = __importDefault(require("lodash/set")); const SpruceError_1 = __importDefault(require("../errors/SpruceError")); const disk_utility_1 = __importDefault(require("../utilities/disk.utility")); class PkgService { constructor(cwd) { this.cwd = cwd; } get(path) { const contents = this.readPackage(); return (0, get_1.default)(contents, path); } set(options) { const { path, value } = options; const contents = this.readPackage(); const updated = (0, set_1.default)(contents, path, value); const destination = this.buildPath(); fs_extra_1.default.outputFileSync(destination, JSON.stringify(updated, null, 2) + '\n'); this._parsedPkg = undefined; } doesExist() { return disk_utility_1.default.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_extra_1.default.readFileSync(packagePath).toString(); const parsed = JSON.parse(contents); this._parsedPkg = parsed; return parsed; } catch (err) { throw new SpruceError_1.default({ code: 'INVALID_PACKAGE_JSON', path: packagePath, originalError: err, errorMessage: err.message, }); } } buildPath() { return path_1.default.join(this.cwd, 'package.json'); } isInstalled(pkg) { try { const contents = this.readPackage(); return (!!contents.dependencies?.[pkg] || !!contents.devDependencies?.[pkg]); } catch (e) { return false; } } deleteLockFile() { const files = ['package-lock.json', 'yarn.lock']; for (const file of files) { const lock = path_1.default.join(this.cwd, file); if (disk_utility_1.default.doesFileExist(lock)) { disk_utility_1.default.deleteFile(lock); } } } stripLatest(name) { return name.replace('@latest', ''); } buildPackageName(dep) { const { name, version } = dep; if (!version) { return name; } return `${name}@${version}`; } } exports.default = PkgService;