@ts-dev-tools/core
Version:
TS dev tools Core
55 lines (54 loc) • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageJsonMerge = void 0;
class PackageJsonMerge {
constructor() { }
static merge(source, update) {
return PackageJsonMerge.mergeObjects(source, update);
}
static mergeValues(source, update) {
if (source === undefined) {
return update;
}
if (!PackageJsonMerge.typesEqual(source, update)) {
throw new Error(`Unable to merge package json value because types are different`);
}
// Deal with arrays
if (Array.isArray(update)) {
return PackageJsonMerge.mergeArrays(source, update);
}
// Deal with objects
if (typeof update === "object") {
return PackageJsonMerge.mergeObjects(source, update);
}
return update;
}
static mergeObjects(source, update) {
for (const updateKey in update) {
if (!Object.hasOwn(update, updateKey)) {
continue;
}
const updateValue = update[updateKey];
const sourceValue = Object.hasOwn(source, updateKey)
? source[updateKey]
: undefined;
source[updateKey] = PackageJsonMerge.mergeValues(sourceValue, updateValue);
}
return source;
}
static mergeArrays(source, update) {
for (const item of update) {
if (!source.includes(item)) {
source.push(item);
}
}
return source;
}
static typesEqual(sourceValue, updateValue) {
if (Array.isArray(sourceValue) && !Array.isArray(updateValue)) {
return false;
}
return typeof sourceValue === typeof updateValue;
}
}
exports.PackageJsonMerge = PackageJsonMerge;