contractDiff.js 4.95 KB
const fs = require("fs");
const path = require("path");
const { buildContract, toMethodFileName } = require("./swaggerInspect");

const ADAPTERS_GLOB_ROOT = path.join(__dirname, "../../api/adapters");

function normalizeParams(parameters = []) {
	return parameters
		.filter((p) => p.in === "query" && p.name !== "sessionId")
		.map((p) => ({
			name: p.name,
			type: p.type || "",
			required: !!p.required,
		}))
		.sort((a, b) => a.name.localeCompare(b.name));
}

function normalizeResponse(contract = {}) {
	return {
		hasPagination: !!contract.response?.pagination,
		paginationFields: contract.response?.pagination?.fields || [],
		fieldNames: (contract.response?.fields || [])
			.filter((f) => !f.name.includes("."))
			.map((f) => f.name.split(".").pop())
			.filter((name) => name !== "code" && name !== "message"),
	};
}

function findTrackedContracts(rootDir = ADAPTERS_GLOB_ROOT) {
	const results = [];
	if (!fs.existsSync(rootDir)) {
		return results;
	}

	function walk(dir) {
		fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => {
			const fullPath = path.join(dir, entry.name);
			if (entry.isDirectory()) {
				walk(fullPath);
				return;
			}
			if (entry.isFile() && entry.name.endsWith(".contract.json")) {
				const raw = JSON.parse(fs.readFileSync(fullPath, "utf8"));
				results.push({
					filePath: fullPath,
					method: raw.method,
					contract: raw,
				});
			}
		});
	}

	walk(rootDir);
	return results;
}

function compareContracts(tracked, fresh) {
	const errors = [];
	const warnings = [];

	const trackedParams = normalizeParams(tracked.request?.parameters);
	const freshParams = normalizeParams(fresh.request?.parameters);

	const trackedMap = new Map(trackedParams.map((p) => [p.name, p]));
	const freshMap = new Map(freshParams.map((p) => [p.name, p]));

	trackedParams.forEach((param) => {
		if (!freshMap.has(param.name)) {
			errors.push(`请求参数已删除: ${param.name}`);
		}
	});

	freshParams.forEach((param) => {
		const old = trackedMap.get(param.name);
		if (!old) {
			if (param.required) {
				errors.push(`新增必填请求参数: ${param.name}`);
			} else {
				warnings.push(`新增可选请求参数: ${param.name}`);
			}
			return;
		}
		if (old.required !== param.required && param.required) {
			errors.push(`请求参数变为必填: ${param.name}`);
		}
		if (old.type && param.type && old.type !== param.type) {
			warnings.push(`请求参数类型变更: ${param.name} (${old.type} -> ${param.type})`);
		}
	});

	const trackedResponse = normalizeResponse(tracked);
	const freshResponse = normalizeResponse(fresh);

	if (trackedResponse.hasPagination && !freshResponse.hasPagination) {
		errors.push("响应分页结构消失");
	}
	if (trackedResponse.hasPagination && !freshResponse.paginationFields.includes("list")) {
		errors.push("分页响应缺少 list 字段");
	}

	trackedResponse.fieldNames.forEach((name) => {
		if (!freshResponse.fieldNames.includes(name)) {
			warnings.push(`响应字段可能移除: ${name}`);
		}
	});

	freshResponse.fieldNames.forEach((name) => {
		if (!trackedResponse.fieldNames.includes(name)) {
			warnings.push(`新增响应字段: ${name}`);
		}
	});

	return { errors, warnings };
}

function diffSnapshotWithTracked(swagger, trackedItems) {
	const report = {
		errors: [],
		warnings: [],
		checked: 0,
	};

	trackedItems.forEach((item) => {
		report.checked += 1;
		let fresh;
		try {
			fresh = buildContract(swagger, item.method);
		} catch (error) {
			report.errors.push(`${item.method}: method 在快照中不存在 (${error.message})`);
			return;
		}

		const { errors, warnings } = compareContracts(item.contract, fresh);
		errors.forEach((message) => report.errors.push(`${item.method}: ${message}`));
		warnings.forEach((message) => report.warnings.push(`${item.method}: ${message}`));
	});

	return report;
}

function diffOnlineSnapshot(oldSwagger, newSwagger) {
	const report = {
		errors: [],
		warnings: [],
		added: [],
		removed: [],
	};

	const oldMethods = new Set(Object.keys(oldSwagger.paths || {})
		.filter((route) => route.startsWith("/router/"))
		.map((route) => route.slice("/router/".length, -"/1.0.0".length)));
	const newMethods = new Set(Object.keys(newSwagger.paths || {})
		.filter((route) => route.startsWith("/router/"))
		.map((route) => route.slice("/router/".length, -"/1.0.0".length)));

	oldMethods.forEach((method) => {
		if (!newMethods.has(method)) {
			report.removed.push(method);
		}
	});
	newMethods.forEach((method) => {
		if (!oldMethods.has(method)) {
			report.added.push(method);
		}
	});

	if (report.removed.length) {
		report.warnings.push(`快照相比线上减少 ${report.removed.length} 个 method,建议 npm run rop:swagger:fetch`);
	}
	if (report.added.length) {
		report.warnings.push(`快照相比线上新增 ${report.added.length} 个 method,建议 npm run rop:swagger:fetch`);
	}

	return report;
}

module.exports = {
	findTrackedContracts,
	compareContracts,
	diffSnapshotWithTracked,
	diffOnlineSnapshot,
	normalizeParams,
	toMethodFileName,
	ADAPTERS_GLOB_ROOT,
};