ropImport.js 11.9 KB
const fs = require("fs");
const path = require("path");
const {
	loadSwagger,
	buildContract,
	formatContractMarkdown,
	buildParamsTemplate,
	buildResponseTemplate,
	methodSuffixToPascal,
	toMethodFileName,
	findMethod,
	DEFAULT_SWAGGER_SNAPSHOT,
} = require("./swaggerInspect");

const SMARTCARLIFE_PREFIX = "dj.api.smartcarlife.";
const API_DIR = path.join(__dirname, "../../api");
const ADAPTERS_ROOT = path.join(API_DIR, "adapters");
const GATEWAY_PREFIXES = new Set(["pc", "pad", "app", "h5", "wx", "mini"]);

const METHOD_PATTERN = /dj\.api\.[a-zA-Z0-9_.]+/g;

function extractMethodFromText(text = "") {
	const matches = text.match(METHOD_PATTERN);
	if (!matches || !matches.length) {
		return null;
	}
	return matches.sort((a, b) => b.length - a.length)[0];
}

function assertSmartcarlifeMethod(method) {
	if (!method || !method.startsWith(SMARTCARLIFE_PREFIX)) {
		throw new Error(`仅支持 ${SMARTCARLIFE_PREFIX}* 接口,收到: ${method || "(empty)"}`);
	}
}

function inferFeatureName(method) {
	assertSmartcarlifeMethod(method);
	const rest = method.slice(SMARTCARLIFE_PREFIX.length);
	const segments = rest.split(".").filter(Boolean);
	if (!segments.length) {
		throw new Error(`无法从 method 推断 feature: ${method}`);
	}
	let start = 0;
	if (GATEWAY_PREFIXES.has(segments[0]) && segments.length > 2) {
		start = 1;
	}
	if (segments.length - start < 2) {
		return segments[start] || segments[0];
	}
	return segments[segments.length - 2];
}

function listApiFiles() {
	if (!fs.existsSync(API_DIR)) {
		return [];
	}
	return fs.readdirSync(API_DIR)
		.filter((name) => name.endsWith(".js") && !name.endsWith(".mock.js") && name !== "request.js")
		.map((name) => path.join(API_DIR, name));
}

function detectApiFile(method, apiOverride) {
	if (apiOverride) {
		const filePath = apiOverride.endsWith(".js")
			? path.resolve(API_DIR, apiOverride)
			: path.resolve(API_DIR, `${apiOverride}.js`);
		if (!fs.existsSync(filePath)) {
			throw new Error(`API 文件不存在: ${filePath}`);
		}
		return filePath;
	}
	const needle = `method = "${method}"`;
	const needle2 = `method = \`${method}\``;
	const hit = listApiFiles().find((filePath) => {
		const content = fs.readFileSync(filePath, "utf8");
		return content.includes(needle) || content.includes(needle2) || content.includes(`"${method}"`);
	});
	return hit || path.join(API_DIR, `${inferFeatureName(method)}.js`);
}

function findExistingApiBinding(apiFilePath, method) {
	const content = fs.readFileSync(apiFilePath, "utf8");
	if (!content.includes(method)) {
		return null;
	}
	const fnStartRegex = /export\s+function\s+(\w+)\s*\([^)]*\)\s*\{/g;
	let match = fnStartRegex.exec(content);
	while (match) {
		const start = match.index;
		const functionName = match[1];
		const nextExport = content.indexOf("export function", start + 1);
		const blockEnd = nextExport === -1 ? content.length : nextExport;
		const block = content.slice(start, blockEnd).trim();
		if (block.includes(`"${method}"`) || block.includes(`\`${method}\``)) {
			return { functionName, block };
		}
		match = fnStartRegex.exec(content);
	}
	return null;
}

function buildActionResponseTemplate(contract) {
	const pascal = methodSuffixToPascal(contract.method);
	const { buildJsdocTypedefs } = require("./swaggerInspect");
	const typedefs = buildJsdocTypedefs(contract);
	return `${typedefs}

/**
 * ${contract.method} 响应 → 页面数据
 * @param {*} [res]
 * @returns {*}
 * @see __contracts__/${toMethodFileName(contract.method)}.contract.md
 */
export function map${pascal}Response(res = {}) {
	return res;
}

export default map${pascal}Response;
`;
}

function getAdapterTemplates(contract) {
	const isPage = !!contract.response.pagination;
	return {
		params: buildParamsTemplate(contract),
		response: isPage ? buildResponseTemplate(contract) : buildActionResponseTemplate(contract),
		pascal: methodSuffixToPascal(contract.method),
		isPage,
	};
}

function ensureDir(dir) {
	if (!fs.existsSync(dir)) {
		fs.mkdirSync(dir, { recursive: true });
	}
}

function writeFileSafe(filePath, content, { dryRun, force }) {
	if (dryRun) {
		return { path: filePath, status: "dry-run" };
	}
	if (fs.existsSync(filePath) && !force) {
		return { path: filePath, status: "skipped" };
	}
	ensureDir(path.dirname(filePath));
	fs.writeFileSync(filePath, content, "utf8");
	return { path: filePath, status: "wrote" };
}

function buildImportPlan(options = {}) {
	const method = options.method || extractMethodFromText(options.text || "");
	if (!method) {
		throw new Error("未找到 ROP method,请传入 --method 或包含 dj.api.* 的文本");
	}
	assertSmartcarlifeMethod(method);

	const feature = options.feature || inferFeatureName(method);
	const adapterDir = path.join(ADAPTERS_ROOT, feature);
	const apiFilePath = detectApiFile(method, options.api);
	const apiFileName = path.basename(apiFilePath);
	const binding = fs.existsSync(apiFilePath)
		? findExistingApiBinding(apiFilePath, method)
		: null;

	let contract;
	try {
		const swagger = options.swaggerDoc || null;
		if (!swagger) {
			throw new Error("swagger required");
		}
		contract = buildContract(swagger, method);
	} catch (error) {
		const wrapped = new Error(`Swagger 中未找到 method: ${method}。请先执行 npm run rop:swagger:fetch`);
		wrapped.cause = error;
		throw wrapped;
	}

	const templates = getAdapterTemplates(contract);
	const methodFile = toMethodFileName(method);
	const files = {
		contractJson: path.join(adapterDir, "__contracts__", `${methodFile}.contract.json`),
		contractMd: path.join(adapterDir, "__contracts__", `${methodFile}.contract.md`),
		params: path.join(adapterDir, `build${templates.pascal}Params.js`),
		response: path.join(adapterDir, `map${templates.pascal}Response.js`),
		api: apiFilePath,
	};

	return {
		method,
		feature,
		contract,
		templates,
		files,
		apiFileName,
		binding,
		adapterDir,
	};
}

function buildMigratedFunctionBody({
	method,
	binding,
	templates,
	mockLoader,
	mockFn,
}) {
	const buildFn = `build${templates.pascal}Params`;
	const mapFn = templates.isPage ? `map${templates.pascal}PageResponse` : `map${templates.pascal}Response`;
	const lines = [];
	lines.push(`export function ${binding.functionName}(data) {`);
	if (mockLoader && mockFn) {
		lines.push(`\tif (${mockLoader}) {`);
		lines.push(`\t\treturn loadAbnormalFlowMock().then((m) => m.${mockFn}(data));`);
		lines.push("\t}");
	}
	lines.push("\tconst payload = {");
	lines.push(`\t\t...${buildFn}(data),`);
	lines.push(`\t\tmethod: "${method}",`);
	lines.push("\t};");
	lines.push(`\treturn request(payload, RequestMethods.POST).then(${mapFn});`);
	lines.push("}");
	return `${lines.join("\n")}\n`;
}

function upsertImportLine(content, importLine) {
	if (content.includes(importLine)) {
		return content;
	}
	const requestImport = content.match(/^import .+ from ["'].\/request["']/m);
	if (requestImport) {
		return content.replace(requestImport[0], `${requestImport[0]}\n${importLine}`);
	}
	return `${importLine}\n${content}`;
}

function migrateApiFile(apiFilePath, plan, { dryRun }) {
	if (!plan.binding) {
		return { path: apiFilePath, status: "skipped", reason: "no-existing-function" };
	}

	const content = fs.readFileSync(apiFilePath, "utf8");
	const buildFn = `build${plan.templates.pascal}Params`;
	const mapFn = plan.templates.isPage
		? `map${plan.templates.pascal}PageResponse`
		: `map${plan.templates.pascal}Response`;

	const importLine = `import { ${buildFn} } from "./adapters/${plan.feature}/build${plan.templates.pascal}Params";`;
	const mapImportLine = `import { ${mapFn} } from "./adapters/${plan.feature}/map${plan.templates.pascal}Response";`;

	let mockFlag = null;
	let mockFn = null;
	if (content.includes("USE_ABNORMAL_FLOW_MOCK")) {
		mockFlag = "USE_ABNORMAL_FLOW_MOCK";
		if (plan.binding.functionName === "getPcAbnormalFlowDeclarationDetail") {
			mockFn = "mockPcAbnormalFlowDeclarationDetail";
		}
		if (plan.binding.functionName === "approvePcAbnormalFlowDeclaration") {
			mockFn = "mockApprovePcAbnormalFlowDeclaration";
		}
	}

	const newBlock = buildMigratedFunctionBody({
		method: plan.method,
		binding: plan.binding,
		templates: plan.templates,
		mockLoader: mockFlag,
		mockFn,
	});

	let next = content.replace(plan.binding.block, newBlock.trim());
	next = upsertImportLine(next, importLine);
	next = upsertImportLine(next, mapImportLine);

	if (dryRun) {
		return { path: apiFilePath, status: "dry-run", preview: newBlock };
	}
	fs.writeFileSync(apiFilePath, next, "utf8");
	return { path: apiFilePath, status: "migrated" };
}

function migrateMockFile(plan, { dryRun }) {
	const mockPath = path.join(API_DIR, "abnormalFlow.mock.js");
	if (!fs.existsSync(mockPath)) {
		return { path: mockPath, status: "skipped", reason: "mock-not-found" };
	}
	if (!plan.method.includes("abnormalFlowDeclaration")) {
		return { path: mockPath, status: "skipped", reason: "not-abnormal-flow" };
	}

	const mapFn = plan.templates.isPage
		? `map${plan.templates.pascal}PageResponse`
		: `map${plan.templates.pascal}Response`;
	const importLine = `import { ${mapFn} } from "./adapters/${plan.feature}/map${plan.templates.pascal}Response";`;
	let content = fs.readFileSync(mockPath, "utf8");
	content = upsertImportLine(content, importLine);

	if (plan.binding?.functionName === "getPcAbnormalFlowDeclarationDetail") {
		content = content.replace(
			/return delay\(\{[\s\S]*?approvalLogs: item\.approvalLogs \|\| \[\],[\s\S]*?\}\);/,
			`return delay(${mapFn}({\n\t\ttradeInfo: buildTradeFields(item),\n\t\tdeclarationInfo: {\n\t\t\tabnormalType: item.abnormalType,\n\t\t\tremark: item.remark,\n\t\t\tcreatedBy: item.createdBy,\n\t\t\tcreatedDate: item.createdDate,\n\t\t\tvoucherImageUrls: item.voucherImageUrls,\n\t\t},\n\t\tapprovalLogs: item.approvalLogs || [],\n\t}));`,
		);
	}
	if (plan.binding?.functionName === "approvePcAbnormalFlowDeclaration") {
		content = content.replace(
			/return delay\(true\);/,
			`return delay(${mapFn}(true));`,
		);
	}

	if (dryRun) {
		return { path: mockPath, status: "dry-run" };
	}
	fs.writeFileSync(mockPath, content, "utf8");
	return { path: mockPath, status: "migrated" };
}

async function runImport(options = {}) {
	const swaggerSource = options.swagger || DEFAULT_SWAGGER_SNAPSHOT;
	const swaggerDoc = await loadSwagger(swaggerSource);
	const plan = buildImportPlan({ ...options, swaggerDoc });
	const writeOpts = { dryRun: !!options.dryRun, force: !!options.force };

	const fileResults = [];
	fileResults.push(writeFileSafe(
		plan.files.contractJson,
		`${JSON.stringify(plan.contract, null, 2)}\n`,
		writeOpts,
	));
	fileResults.push(writeFileSafe(
		plan.files.contractMd,
		`${formatContractMarkdown(plan.contract)}\n`,
		writeOpts,
	));
	fileResults.push(writeFileSafe(plan.files.params, plan.templates.params, writeOpts));
	fileResults.push(writeFileSafe(plan.files.response, plan.templates.response, writeOpts));

	const apiResult = migrateApiFile(plan.files.api, plan, writeOpts);
	fileResults.push(apiResult);

	const mockResult = migrateMockFile(plan, writeOpts);
	fileResults.push(mockResult);

	const report = {
		method: plan.method,
		summary: plan.contract.summary,
		feature: plan.feature,
		apiFile: plan.apiFileName,
		existingFunction: plan.binding?.functionName || null,
		requestParams: plan.contract.request.parameters
			.filter((p) => p.name !== "sessionId")
			.map((p) => ({ name: p.name, required: p.required, type: p.type })),
		responseRoot: plan.contract.response.rootType,
		pagination: !!plan.contract.response.pagination,
		files: fileResults,
		nextSteps: [
			"npm run rop:contract:check",
			plan.binding ? "页面 export 函数名未变,通常无需改 Vue" : "在 src/api 中补充 export 函数",
		],
	};

	if (!options.dryRun) {
		const reportPath = path.join(process.cwd(), "rop-import.report.json");
		fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
		report.reportPath = reportPath;
	}

	return report;
}

module.exports = {
	extractMethodFromText,
	inferFeatureName,
	detectApiFile,
	findExistingApiBinding,
	buildImportPlan,
	buildActionResponseTemplate,
	getAdapterTemplates,
	migrateApiFile,
	migrateMockFile,
	runImport,
	SMARTCARLIFE_PREFIX,
	API_DIR,
	ADAPTERS_ROOT,
};