merge.ts 1.91 KB
import type { JsonValue } from "../types";

import fs from "node:fs";
import fsp from "node:fs/promises";

export async function mergeJson(targetPath: string, mergeObj: Record<string, JsonValue>): Promise<void> {
	const exists = fs.existsSync(targetPath);
	const targetObj: JsonValue = exists ? (JSON.parse(await fsp.readFile(targetPath, "utf8")) as JsonValue) : {};
	const merged = deepMerge(targetObj, mergeObj);
	const sorted = sortKeys(merged);
	await fsp.writeFile(targetPath, JSON.stringify(sorted, null, 2));
}

function sortKeys(obj: JsonValue, parentKey?: string): JsonValue {
	if (Array.isArray(obj)) {
		return obj.map((item) => sortKeys(item, parentKey));
	}
	if (isPlainObject(obj)) {
		// 仅对 dependencies/devDependencies 等依赖 map 按包名排序
		const shouldSort = parentKey && (parentKey === "dependencies" || parentKey === "devDependencies" || parentKey === "peerDependencies" || parentKey === "optionalDependencies");
		const keys = shouldSort ? Object.keys(obj).sort() : Object.keys(obj);
		const sorted: Record<string, JsonValue> = {};
		for (const key of keys) {
			sorted[key] = sortKeys(obj[key], key);
		}
		return sorted;
	}
	return obj;
}

function deepMerge(a: JsonValue, b: JsonValue | undefined): JsonValue {
	if (b === undefined) return a;
	if (Array.isArray(a) && Array.isArray(b)) {
		return [ ...new Set([ ...a, ...b ]) ];
	}
	if (isPlainObject(a) && isPlainObject(b)) {
		const aObj = a as Record<string, JsonValue>;
		const bObj = b as Record<string, JsonValue>;
		const out: Record<string, JsonValue> = { ...aObj };
		for (const key of Object.keys(bObj)) {
			const aValue = aObj[key];
			const bValue = bObj[key];
			if (bValue !== undefined) {
				out[key] = key in aObj && aValue !== undefined ? deepMerge(aValue, bValue) : bValue;
			}
		}
		return out;
	}
	return b;
}

function isPlainObject(v: unknown): v is Record<string, JsonValue> {
	return !!v && typeof v === "object" && !Array.isArray(v);
}