const fs = require('fs'); const path = require('path'); const projectRoot = path.resolve(__dirname, '..'); const controllerRoot = path.join(projectRoot, 'src', 'controller', 'web'); const socketRoot = path.join(projectRoot, 'src', 'socket'); function readText(filePath) { return fs.readFileSync(filePath, 'utf8'); } function listFiles(dirPath) { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); const files = []; for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); if (entry.isDirectory()) { files.push(...listFiles(fullPath)); continue; } if (entry.isFile() && entry.name.endsWith('.js')) { files.push(fullPath); } } return files; } function toPosixPath(filePath) { return path.relative(projectRoot, filePath).replace(/\\/g, '/'); } function uniq(values) { return [...new Set(values.filter(Boolean))]; } function parseStringArray(source, variableName) { const pattern = new RegExp(`const\\s+${variableName}\\s*=\\s*\\[([\\s\\S]*?)\\]`, 'm'); const match = source.match(pattern); if (!match) { return []; } return [...match[1].matchAll(/'([^']+)'/g)].map((item) => item[1]); } function extractCommentValue(comment, key) { const pattern = new RegExp(`#${key}\\s+(.+)`); const line = comment .split(/\r?\n/) .map((item) => item.replace(/^\s*\*\s?/, '').trim()) .find((item) => pattern.test(item)); if (!line) { return ''; } return line.replace(pattern, '$1').trim(); } function parseObjectKeys(text) { return uniq( text .split(',') .map((item) => item.trim()) .filter(Boolean) .map((item) => item.split(':')[0].trim()) .filter((item) => item && !item.startsWith('...')) ); } function getParamBlocks(routeBody) { const blocks = []; for (const match of routeBody.matchAll(/const\s*\{([\s\S]*?)\}\s*=\s*request\.(body|query);/g)) { blocks.push({ source: match[2], params: uniq( match[1] .split(',') .map((item) => item.trim()) .filter(Boolean) .map((item) => item.replace(/=.*$/, '').trim()) ), }); } return blocks; } function getRequiredParams(routeBody) { const required = []; for (const match of routeBody.matchAll(/checkRequestParams\s*\(\s*\{([\s\S]*?)\}\s*\)/g)) { required.push(...parseObjectKeys(match[1])); } return uniq(required); } function detectResponseCookies(routeBody) { const cookies = []; for (const match of routeBody.matchAll(/response\.cookie\(([^,]+),/g)) { cookies.push(match[1].trim()); } return uniq(cookies); } function detectBusinessCall(routeBody) { const match = routeBody.match(/const\s+result\s*=\s*await\s+([\w$.]+)\s*\(/); return match ? match[1] : ''; } function normalizeService(fullPath) { if ( fullPath.startsWith('/api/web/system-') || fullPath.includes('/system-login') || fullPath.includes('/system-logout') ) { return 'super-api'; } return 'api'; } function parseControllers(loginAuthIgnoreApi, loginRoleIgnoreApi) { const controllerFiles = listFiles(controllerRoot); const endpoints = []; for (const filePath of controllerFiles) { const source = readText(filePath); const routePattern = /\/\*\*([\s\S]*?)\*\/\s*router\.(get|post)\('([^']+)'\s*,\s*async function\(request, response\) \{([\s\S]*?)\n\}\)\s*;?/g; for (const match of source.matchAll(routePattern)) { const comment = match[1]; const method = match[2].toUpperCase(); const subPath = match[3]; const routeBody = match[4]; const annotatedPath = extractCommentValue(comment, 'controller'); const fullPath = annotatedPath ? annotatedPath.split(/\s+/).slice(1).join(' ') : subPath; const description = extractCommentValue(comment, 'desc'); const paramBlocks = getParamBlocks(routeBody); const requiredParams = getRequiredParams(routeBody); const paramSource = paramBlocks.length === 1 ? paramBlocks[0].source : (paramBlocks[0]?.source || 'none'); const params = []; const paramsByName = new Map(); for (const block of paramBlocks) { for (const name of block.params) { paramsByName.set(name, { name, source: block.source, required: requiredParams.includes(name), }); } } for (const name of requiredParams) { if (!paramsByName.has(name)) { paramsByName.set(name, { name, source: paramSource, required: true, }); } } params.push(...paramsByName.values()); endpoints.push({ controllerFile: toPosixPath(filePath), module: path.basename(path.dirname(filePath)), method, path: fullPath || subPath, subPath, description, service: normalizeService(fullPath || subPath), auth: { loginRequired: !loginAuthIgnoreApi.includes(fullPath || subPath), roleCheckRequired: !loginRoleIgnoreApi.includes(fullPath || subPath), tokenType: (fullPath || subPath).includes('/system-') ? 'system-cookie-or-header' : 'user-cookie-or-header', }, request: { paramSource, params, setsCookies: detectResponseCookies(routeBody), }, response: { envelope: { success: 'boolean', code: 'number', msg: 'string', data: 'object|array|string|number|boolean', }, businessResult: detectBusinessCall(routeBody), commonErrorCodes: [400, 403, 404, 500, 504], }, }); } } return endpoints.sort((left, right) => left.path.localeCompare(right.path)); } function parseRequireMap(source) { const map = new Map(); for (const match of source.matchAll(/const\s+(\w+)\s*=\s*require\("([^"]+)"\);/g)) { map.set(match[1], match[2]); } for (const match of source.matchAll(/const\s+(\w+)\s*=\s*require\('([^']+)'\);/g)) { map.set(match[1], match[2]); } return map; } function findRequiredModule(source, alias) { const escapedAlias = alias.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const patterns = [ new RegExp(`const\\s+${escapedAlias}\\s*=\\s*require\\(\"([^\"]+)\"\\)`), new RegExp(`const\\s+${escapedAlias}\\s*=\\s*require\\('([^']+)'\\)`), ]; for (const pattern of patterns) { const match = source.match(pattern); if (match) { return match[1]; } } return ''; } function extractHandlerFunctionInfo(handlerPath, functionName) { const source = readText(handlerPath); const params = []; const dataDestructure = source.match(/const\s*\{([\s\S]*?)\}\s*=\s*data;/); if (dataDestructure) { params.push(...uniq(dataDestructure[1].split(',').map((item) => item.trim()).filter(Boolean).map((item) => item.replace(/=.*$/, '').trim()))); } const emits = uniq([ ...[...source.matchAll(/\.emit\(socketClientEvent\.(\w+)/g)].map((item) => item[1]), ...[...source.matchAll(/\.emit\('([^']+)'/g)].map((item) => item[1]), ...[...source.matchAll(/\.emit\("([^"]+)"/g)].map((item) => item[1]), ]); return { handlerFile: toPosixPath(handlerPath), handlerFunction: functionName, params, emits, }; } function parseSocketDocs() { const connectPath = path.join(socketRoot, 'connect.js'); const connectSource = readText(connectPath); const inboundEvents = []; for (const match of connectSource.matchAll(/socket\.on\(socketServerEvent\.(\w+),\s*\(data\)\s*=>\s*\{\s*(\w+)\.(\w+)\(io, socket, data\)/g)) { const eventName = match[1]; const alias = match[2]; const functionName = match[3]; const relativeHandlerPath = findRequiredModule(connectSource, alias); if (!relativeHandlerPath) { inboundEvents.push({ event: eventName, handlerFile: '', handlerFunction: functionName, params: [], emits: [], }); continue; } const handlerPath = path.resolve(path.dirname(connectPath), relativeHandlerPath + '.js'); inboundEvents.push({ event: eventName, ...extractHandlerFunctionInfo(handlerPath, functionName), }); } const serverEventPath = path.join(socketRoot, 'event', 'server_event.js'); const clientEventPath = path.join(socketRoot, 'event', 'client_event.js'); const serverSource = readText(serverEventPath); const clientSource = readText(clientEventPath); const parseEventEnum = (source) => { const events = []; let pendingDescription = ''; for (const rawLine of source.split(/\r?\n/)) { const line = rawLine.trim(); if (line.startsWith('//')) { pendingDescription = line.replace(/^\/\/\s*/, '').trim(); continue; } const match = line.match(/(\w+)\s*:\s*['"]([^'"]+)['"]/); if (!match) { continue; } events.push({ key: match[1], event: match[2], description: pendingDescription, }); pendingDescription = ''; } return events; }; const outboundEnum = parseEventEnum(clientSource); const inboundEnum = parseEventEnum(serverSource); return { transport: 'socket.io', entryFile: toPosixPath(path.join(socketRoot, 'index.js')), serverEventEnumFile: toPosixPath(serverEventPath), clientEventEnumFile: toPosixPath(clientEventPath), inboundEvents: inboundEnum.map((eventInfo) => { const detail = inboundEvents.find((item) => item.event === eventInfo.key || item.event === eventInfo.event); return { event: eventInfo.event, key: eventInfo.key, description: eventInfo.description, handlerFile: detail?.handlerFile || '', handlerFunction: detail?.handlerFunction || '', params: detail?.params || [], emits: detail?.emits || [], }; }), outboundEvents: outboundEnum, }; } function groupHttpEndpoints(endpoints) { const groups = {}; for (const endpoint of endpoints) { if (!groups[endpoint.service]) { groups[endpoint.service] = []; } groups[endpoint.service].push(endpoint); } return groups; } function writeJson(fileName, payload) { const outputPath = path.join(__dirname, fileName); fs.writeFileSync(outputPath, JSON.stringify(payload, null, 2) + '\n', 'utf8'); } function main() { const loginAuthSource = readText(path.join(projectRoot, 'src', 'middleware', 'loginAuth.js')); const loginRoleSource = readText(path.join(projectRoot, 'src', 'middleware', 'loginRole.js')); const loginAuthIgnoreApi = parseStringArray(loginAuthSource, 'loginAuthIngoreApi'); const loginRoleIgnoreApi = parseStringArray(loginRoleSource, 'loginRoleIngoreApi'); const httpEndpoints = parseControllers(loginAuthIgnoreApi, loginRoleIgnoreApi); const socketDocs = parseSocketDocs(); const grouped = groupHttpEndpoints(httpEndpoints); const generatedAt = new Date().toISOString(); writeJson('service_overview.json', { generatedAt, project: 'tl-rtc-app', services: [ { service: 'api', entryFile: 'tlapi.js', defaultPortEnv: 'tl_rtc_app_api_port', defaultPort: 9096, staticRoot: 'web-dist/', routePrefix: '/api/web', endpointCount: grouped.api ? grouped.api.length : 0, }, { service: 'super-api', entryFile: 'tlsuperapi.js', defaultPortEnv: 'tl_rtc_app_super_api_port', defaultPort: 9098, staticRoot: 'system-dist/', routePrefix: '/api/web', endpointCount: grouped['super-api'] ? grouped['super-api'].length : 0, }, { service: 'socket', entryFile: 'tlsocket.js', defaultPortEnv: 'tl_rtc_app_socket_port', defaultPort: 9097, transport: 'socket.io', inboundEventCount: socketDocs.inboundEvents.length, outboundEventCount: socketDocs.outboundEvents.length, }, ], commonResponseEnvelope: { success: 'boolean', code: 'number', msg: 'string', data: 'object|array|string|number|boolean', }, }); writeJson('http_api.json', { generatedAt, routeRoot: '/api/web', totalEndpoints: httpEndpoints.length, endpoints: httpEndpoints, }); writeJson('socket_api.json', { generatedAt, ...socketDocs, }); writeJson('api_index.json', { generatedAt, files: [ 'service_overview.json', 'http_api.json', 'socket_api.json', ], }); } main();