@ts-dev-tools/core
Version:
TS dev tools Core
84 lines (83 loc) • 2.75 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageJson = void 0;
const node_path_1 = require("node:path");
const FileService_1 = require("./FileService");
const PackageJsonMerge_1 = require("./PackageJsonMerge");
class PackageJson {
path;
static PACKAGE_JSON_FILE_NAME = "package.json";
content = undefined;
constructor(path) {
this.path = path;
if (!FileService_1.FileService.fileExists(this.path)) {
throw new Error(`Package.json "${this.path}" does not exist`);
}
}
getPath() {
return this.path;
}
getContent() {
if (this.content) {
return this.content;
}
this.content = JSON.parse(FileService_1.FileService.getFileContent(this.path));
return this.content;
}
setContent(content) {
this.content = content;
this.write();
}
getPackageName() {
return this.getContent().name;
}
getPackageVersion() {
return this.getContent().version;
}
isPrivate() {
return this.getContent().private === true;
}
getTsDevToolsVersion() {
const tsDevToolsConfig = this.getContent().tsDevTools;
const version = tsDevToolsConfig?.version;
return version;
}
getDependenciesPackageNames() {
const dependencies = this.getContent().dependencies;
return dependencies ? Object.keys(dependencies) : [];
}
getDevDependenciesPackageNames() {
const devDependencies = this.getContent().devDependencies;
return devDependencies ? Object.keys(devDependencies) : [];
}
getAllDependenciesPackageNames() {
return Array.from(new Set([
...this.getDependenciesPackageNames(),
...this.getDevDependenciesPackageNames(),
]));
}
hasDependency(packageName) {
return this.getAllDependenciesPackageNames().includes(packageName);
}
merge(update) {
this.content = PackageJsonMerge_1.PackageJsonMerge.merge(this.getContent(), update);
this.write();
}
backup() {
const backupPath = `${this.path}.backup`;
FileService_1.FileService.copyFile(this.path, backupPath);
return backupPath;
}
restore(backupPath) {
FileService_1.FileService.copyFile(backupPath, this.path);
this.content = undefined;
}
write() {
FileService_1.FileService.putFileContent(this.path, JSON.stringify(this.content, null, 2));
}
static fromDirPath(dirPath) {
const packageJsonPath = (0, node_path_1.join)(dirPath, PackageJson.PACKAGE_JSON_FILE_NAME);
return new PackageJson(packageJsonPath);
}
}
exports.PackageJson = PackageJson;