import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { API_DOC_AGENT_API_LIST_UPDATE_CONFIG } from "./config.mjs"; 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}`; } function getTodayStamp(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"); return `${year}${month}${day}`; } function sanitizeFileName(name) { const normalized = name.toLowerCase().replace(/[^a-z0-9._-]+/g, "_"); return normalized.replace(/^_+|_+$/g, "") || "api-list"; } async function writeJson(filePath, data) { await mkdir(path.dirname(filePath), { recursive: true }); await writeFile(filePath, `${JSON.stringify(data, null, 2)}\n`, "utf8"); } async function writeText(filePath, text) { await mkdir(path.dirname(filePath), { recursive: true }); await writeFile(filePath, `${text.trimEnd()}\n`, "utf8"); } async function listTsFiles(rootDir) { const stack = [rootDir]; const files = []; while (stack.length > 0) { const current = stack.pop(); const entries = await readdir(current, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(current, entry.name); if (entry.isDirectory()) { stack.push(fullPath); continue; } if (entry.isFile() && entry.name.endsWith(".ts")) { files.push(fullPath); } } } return files.sort((a, b) => a.localeCompare(b, "zh-CN")); } function createCommentMask(content) { const mask = new Array(content.length).fill(false); let i = 0; let inSingle = false; let inDouble = false; let inTemplate = false; let inLineComment = false; let inBlockComment = false; while (i < content.length) { const ch = content[i]; const next = content[i + 1] ?? ""; const prev = content[i - 1] ?? ""; if (inLineComment) { mask[i] = true; if (ch === "\n") { inLineComment = false; } i += 1; continue; } if (inBlockComment) { mask[i] = true; if (ch === "*" && next === "/") { mask[i + 1] = true; inBlockComment = false; i += 2; continue; } i += 1; continue; } if (!inDouble && !inTemplate && ch === "'" && prev !== "\\") { inSingle = !inSingle; i += 1; continue; } if (!inSingle && !inTemplate && ch === '"' && prev !== "\\") { inDouble = !inDouble; i += 1; continue; } if (!inSingle && !inDouble && ch === "`" && prev !== "\\") { inTemplate = !inTemplate; i += 1; continue; } if (!inSingle && !inDouble && !inTemplate) { if (ch === "/" && next === "/") { mask[i] = true; mask[i + 1] = true; inLineComment = true; i += 2; continue; } if (ch === "/" && next === "*") { mask[i] = true; mask[i + 1] = true; inBlockComment = true; i += 2; continue; } } i += 1; } return mask; } function buildExportAnchors(content) { const anchors = []; const reg = /export\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)|export\s+const\s+([A-Za-z_$][\w$]*)/g; for (const match of content.matchAll(reg)) { anchors.push({ index: match.index ?? 0, name: match[1] || match[2] || "", }); } return anchors; } function getNearestExportName(anchors, index) { let name = ""; for (const item of anchors) { if (item.index > index) { break; } name = item.name; } return name || null; } function detectPlaceholder(content, index) { const start = Math.max(0, index - 160); const end = Math.min(content.length, index + 160); const context = content.slice(start, end); return /(占位|placeholder|todo)/i.test(context); } function parseInterfacesFromFile(content, filePath, srcApiDir) { const commentMask = createCommentMask(content); const exportAnchors = buildExportAnchors(content); const relPath = path.relative(srcApiDir, filePath).replaceAll("\\", "/"); const segments = relPath.split("/"); const moduleName = segments[0] || "unknown"; const fileName = segments[segments.length - 1] || ""; const matches = []; const methodRegex = /params\s*:\s*\{[\s\S]*?\bmethod\s*:\s*['"`]([^'"`]+)['"`]/g; for (const match of content.matchAll(methodRegex)) { const method = (match[1] || "").trim(); if (!method) { continue; } const index = match.index ?? 0; const isCommented = Boolean(commentMask[index]); const functionName = getNearestExportName(exportAnchors, index); const requestStart = content.lastIndexOf("request(", index); const requestWindow = requestStart >= 0 ? content.slice(requestStart, Math.min(content.length, index + 280)) : content.slice(index, index + 280); const httpMethod = requestWindow.match(/\bmethod\s*:\s*['"`](get|post|put|delete|patch|options|head)['"`]/i)?.[1] ?? "post"; matches.push({ moduleName, fileName, filePath: relPath, interfaceName: functionName || method, method, httpMethod: httpMethod.toLowerCase(), isEnabled: !isCommented, isPlaceholder: detectPlaceholder(content, index), }); } return matches; } function uniqueInterfaces(items) { const map = new Map(); for (const item of items) { const key = `${item.filePath}::${item.method}`; if (!map.has(key)) { map.set(key, item); } } return [...map.values()]; } function buildMarkdown(payload) { const lines = [ "# 接口", "", `- 更新时间: ${payload.generatedAtLocal}`, `- 扫描目录: \`${payload.source.srcApiDir}\``, `- 模块数: ${payload.summary.moduleCount}`, `- API 文件数: ${payload.summary.fileCount}`, `- 接口数: ${payload.summary.interfaceCount}`, `- 已启用: ${payload.summary.enabledCount}`, `- 占位接口: ${payload.summary.placeholderCount}`, "", "## 模块统计", "", "| 模块 | 文件数 | 接口数 | 已启用 | 占位 |", "| --- | ---: | ---: | ---: | ---: |", ]; for (const module of payload.modules) { lines.push( `| ${module.moduleName} | ${module.fileCount} | ${module.interfaceCount} | ${module.enabledCount} | ${module.placeholderCount} |`, ); } lines.push("", "## 接口明细", "", "| 模块 | 接口名 | method | HTTP Method | 启用 | 占位 | 文件 |", "| --- | --- | --- | --- | --- | --- | --- |"); for (const item of payload.interfaces) { lines.push( `| ${item.moduleName} | ${item.interfaceName} | ${item.method} | ${item.httpMethod.toUpperCase()} | ${item.isEnabled ? "是" : "否"} | ${item.isPlaceholder ? "是" : "否"} | ${item.filePath} |`, ); } return lines.join("\n"); } export async function runScript(args = []) { const outputName = args[0] ? sanitizeFileName(args[0]) : "api-list-update"; const now = new Date(); const srcApiDir = API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.srcApiDir; const files = await listTsFiles(srcApiDir); const allInterfaces = []; for (const filePath of files) { const content = await readFile(filePath, "utf8"); const parsed = parseInterfacesFromFile(content, filePath, srcApiDir); allInterfaces.push(...parsed); } const interfaces = uniqueInterfaces(allInterfaces).sort((a, b) => { if (a.moduleName !== b.moduleName) { return a.moduleName.localeCompare(b.moduleName, "zh-CN"); } if (a.filePath !== b.filePath) { return a.filePath.localeCompare(b.filePath, "zh-CN"); } return a.method.localeCompare(b.method, "zh-CN"); }); const moduleMap = new Map(); for (const item of interfaces) { const current = moduleMap.get(item.moduleName) ?? { moduleName: item.moduleName, fileSet: new Set(), interfaceCount: 0, enabledCount: 0, placeholderCount: 0, }; current.fileSet.add(item.filePath); current.interfaceCount += 1; if (item.isEnabled) { current.enabledCount += 1; } if (item.isPlaceholder) { current.placeholderCount += 1; } moduleMap.set(item.moduleName, current); } const modules = [...moduleMap.values()] .map((item) => ({ moduleName: item.moduleName, fileCount: item.fileSet.size, interfaceCount: item.interfaceCount, enabledCount: item.enabledCount, placeholderCount: item.placeholderCount, })) .sort((a, b) => a.moduleName.localeCompare(b.moduleName, "zh-CN")); const payload = { script: "api-list-update", generatedAt: now.toISOString(), generatedAtLocal: formatLocalDateTime(now), source: { srcApiDir, }, summary: { moduleCount: modules.length, fileCount: new Set(interfaces.map((item) => item.filePath)).size, interfaceCount: interfaces.length, enabledCount: interfaces.filter((item) => item.isEnabled).length, placeholderCount: interfaces.filter((item) => item.isPlaceholder).length, }, modules, interfaces, }; const markdown = buildMarkdown(payload); await writeText(API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.outputDocs, markdown); await writeText(API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.outputConfig, markdown); const resultFilePath = path.join( API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.resultDir, getTodayStamp(now), `${outputName}.json`, ); await writeJson(resultFilePath, payload); console.log(`执行时间: ${payload.generatedAtLocal}`); console.log(`已更新接口清单文档: ${API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.outputDocs}`); console.log(`已同步配置文档: ${API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.outputConfig}`); console.log(`结果文件: ${resultFilePath}`); console.log(JSON.stringify(payload.summary, null, 2)); }