feat(v0.11+): apis search --field= 字段级搜索 (P0 字段盲猜)

Phase 1 审计 (cmd-review/apis.md) 标记 P0 必补:
- 解决 AI 知道字段名 (如 f_user_name) 但不知道哪些 API 接受/返回该字段
- 解决 'AI 盲猜哪个 API 接受字段' 痛点 (盲点根因 B)

新增 dacli apis search --field=<f>:
- 遍历 OpenAPI components.schemas, 模糊匹配字段名 (--exact 可精确)
- 输出: 包含字段的 schema 列表 + 引用这些 schema 的 API 端点
- AI 工作流: search → info 精准拿 schema 详情
- 默认 --limit=50 防止输出过大

依赖: loadOpenApi (apis/_cache.ts 已有, 12h 缓存)

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-06-25 15:03:35 +08:00
1 parent 5f663eb494
commit 7b8f9b1b45
2 files changed
+155

No files matched your search

+3
View File
@@ -2,12 +2,14 @@
* commands/apis/index.ts — apis 父命令 (JNPF OpenAPI 查询)
*
* v0.7+: 4 子命令 (list/info/refresh/status) + 12h in-memory 缓存 (apis/_cache.ts)
* v0.11+: 5 子命令 (+search 字段级搜索, P0 字段盲猜)
*/
import { Command } from 'commander'
import { buildApisListCommand } from './list.ts'
import { buildApisInfoCommand } from './info.ts'
import { buildApisRefreshCommand } from './refresh.ts'
import { buildApisStatusCommand } from './status.ts'
import { buildApisSearchCommand } from './search.ts'
export function buildApisCommand(): Command {
const cmd = new Command('apis').description('JNPF 平台 API 查 (OpenAPI, 12h in-memory 缓存)')
@@ -15,5 +17,6 @@ export function buildApisCommand(): Command {
cmd.addCommand(buildApisInfoCommand())
cmd.addCommand(buildApisRefreshCommand())
cmd.addCommand(buildApisStatusCommand())
cmd.addCommand(buildApisSearchCommand())
return cmd
}
+152
View File
@@ -0,0 +1,152 @@
/**
* commands/apis/search.ts — 按字段名搜索 API
*
* v0.11+ P0 新增: AI 知道字段名 (如 f_user_name) 但不知道哪些 API 接受/返回该字段
* 解决 "AI 盲猜哪个 API 接受字段" 痛点
*
* 工作原理:
* 遍历 OpenAPI components.schemas, 匹配 properties 中的字段名
* 输出: 包含该字段的所有 schema + 引用这些 schema 的 API 端点
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { loadOpenApi, type OpenApiDoc } from './_cache.ts'
interface Opts {
field: string
json?: boolean
limit?: string
exact?: boolean
}
interface SchemaRef {
name: string
type?: string
description?: string
required: boolean
}
interface ApiRef {
method: string
path: string
summary?: string
direction: 'request' | 'response'
}
interface SearchResult {
field: string
schemas: SchemaRef[]
apis: ApiRef[]
}
function searchInSchemas(openapi: OpenApiDoc, fieldName: string, exact: boolean): SchemaRef[] {
const results: SchemaRef[] = []
const schemas = openapi.components?.schemas || {}
for (const [schemaName, schemaVal] of Object.entries(schemas)) {
if (!schemaVal || typeof schemaVal !== 'object') continue
const s = schemaVal as Record<string, unknown>
const props = (s.properties as Record<string, unknown>) || {}
const requiredList = (s.required as string[]) || []
for (const propName of Object.keys(props)) {
const matched = exact ? propName === fieldName : propName.toLowerCase().includes(fieldName.toLowerCase())
if (matched) {
const propVal = props[propName] as Record<string, unknown> | undefined
results.push({
name: schemaName,
type: (propVal?.type as string) || (propVal?.$ref as string)?.split('/').pop(),
description: (propVal?.description as string) || '',
required: requiredList.includes(propName),
})
}
}
}
return results
}
function searchInPaths(openapi: OpenApiDoc, schemaNames: Set<string>): ApiRef[] {
const results: ApiRef[] = []
for (const [path, pathItem] of Object.entries(openapi.paths || {})) {
for (const [method, op] of Object.entries(pathItem || {})) {
if (method.startsWith('x-') || !['get', 'post', 'put', 'delete', 'patch'].includes(method.toLowerCase())) continue
const opObj = op as Record<string, unknown>
// 检查 requestBody / parameters / responses 引用了目标 schema
const body = JSON.stringify(opObj)
if (schemaNames.size === 0 || [...schemaNames].some((n) => body.includes(n))) {
results.push({
method: method.toUpperCase(),
path,
summary: opObj.summary as string | undefined,
direction: body.includes('RequestBody') || body.includes('"in":"body"') || body.includes('"in":"query"') ? 'request' : 'response',
})
}
}
}
return results
}
export function buildApisSearchCommand(): Command {
const cmd = new Command('search')
.description('按字段名搜索 API (返回包含该字段的 schema + 引用这些 schema 的 API 端点)')
.requiredOption('--field <f>', '字段名 (如 f_user_name, 默认模糊匹配)')
.option('--exact', '精确匹配字段名', false)
.option('--limit <n>', 'API 列表最大条数 (默认 50)', '50')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const openapi = await loadOpenApi(c)
const schemas = searchInSchemas(openapi, opts.field, opts.exact || false)
const schemaNames = new Set(schemas.map((s) => s.name))
const apis = searchInPaths(openapi, schemaNames).slice(0, parseInt(opts.limit || '50', 10))
const result: SearchResult = {
field: opts.field,
schemas: [...new Map(schemas.map((s) => [`${s.name}.${s.type}`, s])).values()],
apis,
}
if (opts.json) {
printJson(result)
return
}
log.info(`字段 "${opts.field}" 匹配 ${result.schemas.length} 个 schema, ${result.apis.length} 个 API`)
if (result.schemas.length === 0) {
log.warn('无 schema 匹配. 提示: 字段名通常是 f_xxx 形式 (snake_case), 可省略前缀试试')
return
}
console.log('\n# 包含该字段的 Schema:')
console.log('SCHEMA'.padEnd(40) + 'TYPE'.padEnd(20) + 'REQUIRED DESCRIPTION')
console.log('-'.repeat(95))
for (const s of result.schemas) {
console.log(`${s.name.padEnd(40)}${(s.type || '-').padEnd(20)}${s.required ? 'YES' : 'no'.padEnd(9)} ${(s.description || '').slice(0, 40)}`)
}
console.log('\n# 引用这些 Schema 的 API:')
console.log('METHOD'.padEnd(8) + 'PATH'.padEnd(60) + 'DIRECTION SUMMARY')
console.log('-'.repeat(115))
for (const a of result.apis) {
console.log(`${a.method.padEnd(8)}${a.path.padEnd(60)}${a.direction.padEnd(10)} ${(a.summary || '').slice(0, 40)}`)
}
log.info(`\n💡 用法: dacli apis info "${result.apis[0]?.method} ${result.apis[0]?.path}" (看 schema 详情)`)
})
installAiHelpHook(cmd, {
purpose: '按字段名搜索 API (P0 字段盲猜痛点, AI 知道 f_xxx 但不知道哪个 API 接受)',
required: { '--field': '字段名' },
optional: {
'--exact': '精确匹配字段名',
'--limit': 'API 列表最大条数',
'--json': '原始 JSON 输出',
},
example: [
'dacli apis search --field=f_user_name',
'dacli apis search --field=enCode --exact',
],
notes: [
'v0.11+ 新增, 解决 Phase 1 审计 (cmd-review/apis.md) 标记的 P0 字段盲猜痛点',
'默认模糊匹配 (--field=enCode 匹配 fullName/enCode/encode 等), --exact 精确',
],
})
return cmd
}