import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { API_DOC_INTERFACE_SCRIPT_CONFIG } from "./config.mjs"; function sanitizeFileName(name) { const normalized = name.toLowerCase().replace(/[^a-z0-9._-]+/g, "_"); return normalized.replace(/^_+|_+$/g, "") || "interface"; } async function readJson(filePath) { const content = await readFile(filePath, "utf8"); return JSON.parse(content); } async function readJsonIfExists(filePath, fallbackValue = null) { try { return await readJson(filePath); } catch (error) { if (error?.code === "ENOENT") { return fallbackValue; } throw error; } } async function getModuleSnapshotFilePath(targetDir) { const targetPath = path.join(targetDir, API_DOC_INTERFACE_SCRIPT_CONFIG.file.moduleSnapshotName); const parsed = await readJsonIfExists(targetPath, null); return parsed ? targetPath : null; } async function listModuleFolders(moduleRootDir) { const entries = await readdir(moduleRootDir, { withFileTypes: true }); return entries .filter((entry) => entry.isDirectory()) .map((entry) => entry.name) .sort((a, b) => a.localeCompare(b, "zh-CN")); } async function writeJson(filePath, data) { await mkdir(path.dirname(filePath), { recursive: true }); await writeFile(filePath, `${JSON.stringify(data, null, 2)}\n`, "utf8"); } function getTodayStamp() { const now = new Date(); const year = String(now.getFullYear()); const month = String(now.getMonth() + 1).padStart(2, "0"); const day = String(now.getDate()).padStart(2, "0"); return `${year}${month}${day}`; } function formatLocalDateTime(input = new Date()) { const date = input instanceof Date ? input : new Date(input); const year = String(date.getFullYear()); const month = String(date.getMonth() + 1).padStart(2, "0"); const day = String(date.getDate()).padStart(2, "0"); const hours = String(date.getHours()).padStart(2, "0"); const minutes = String(date.getMinutes()).padStart(2, "0"); const seconds = String(date.getSeconds()).padStart(2, "0"); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; } async function resolveInterface(method) { const moduleFolders = await listModuleFolders(API_DOC_INTERFACE_SCRIPT_CONFIG.file.moduleDir); const moduleInterfaceMap = new Map(); const moduleSourceFiles = []; for (const folderName of moduleFolders) { const folderPath = path.join(API_DOC_INTERFACE_SCRIPT_CONFIG.file.moduleDir, folderName); const lifecycle = await readJsonIfExists(path.join(folderPath, "_module.lifecycle.json"), null); if (lifecycle?.status === "deleted") { continue; } const moduleFile = await getModuleSnapshotFilePath(folderPath); if (!moduleFile) { continue; } moduleSourceFiles.push(moduleFile); const moduleDoc = await readJson(moduleFile); const moduleMeta = moduleDoc?.module ?? {}; const moduleInterfaces = Array.isArray(moduleDoc?.interfaces) ? moduleDoc.interfaces : []; for (const item of moduleInterfaces) { if (!item?.method || moduleInterfaceMap.has(item.method)) { continue; } moduleInterfaceMap.set(item.method, { method: item.method, title: item.title, description: item.description, endpoint: item.endpoint, authRequired: item.authRequired, loginRequired: item.loginRequired, status: { isUsed: Boolean(item?.status?.isUsed), isPlaceholder: Boolean(item?.status?.isPlaceholder), }, params: item.params ?? [], response: item.response ?? [], moduleName: moduleMeta?.name ?? folderName, moduleKey: moduleMeta?.key ?? folderName, moduleFolder: moduleMeta?.folder ?? folderName, moduleFile, }); } } const target = moduleInterfaceMap.get(method); if (!target) { return { method, available: false, reason: "Method not found in latest active module snapshots.", check: { isUsed: false, isPlaceholder: false }, source: { moduleFiles: moduleSourceFiles }, interfaceSpec: null, }; } const isUsed = Boolean(target?.status?.isUsed); const isPlaceholder = Boolean(target?.status?.isPlaceholder); const available = isUsed && !isPlaceholder; return { method, available, reason: available ? "Method is usable for coding." : "Method does not satisfy availability rule: isUsed=true and isPlaceholder=false.", check: { isUsed, isPlaceholder }, source: { moduleFile: target.moduleFile, }, interfaceSpec: available ? { moduleName: target.moduleName, moduleKey: target.moduleKey, moduleFolder: target.moduleFolder, method: target.method, title: target.title, description: target.description, endpoint: target.endpoint, authRequired: target.authRequired, loginRequired: target.loginRequired, params: target.params, response: target.response, } : null, }; } export async function runScript(args = []) { const method = args[0]; if (!method) { throw new Error("请提供目标接口名,例如: npm run apiagent -- storage.receiving.bindStore"); } const now = new Date(); const resolvedAt = now.toISOString(); const result = await resolveInterface(method.trim()); const payload = { script: "interface", resolvedAt, resolvedAtLocal: formatLocalDateTime(now), ...result, }; const outputFilePath = path.join( API_DOC_INTERFACE_SCRIPT_CONFIG.file.resultDir, getTodayStamp(), `${sanitizeFileName(method)}.json`, ); await writeJson(outputFilePath, payload); console.log(`执行时间: ${payload.resolvedAtLocal}`); console.log(JSON.stringify(payload, null, 2)); console.log(`Agent 查询结果已写入: ${outputFilePath}`); }