init: TS 版 dacli v0.7 baseline (8 父命令/26+ 子命令, 0.4MB, .claude/skills/dacli-ts)

参考 boot/ 仓库结构初始化, 同步到 gitea:3000/ssw/dacli (private).

包括:
- src/  8 父命令 (form/menu/dm/dict/di/apis/doc/workflow + login/status) + core (client/crypto/help/log/types/config)
- src/schema/ FieldBuilder (从 JNPF web 源码提取, 避免 53 个手写 builder)
- tests/ vitest 单元 + playwright E2E (含 workSystem/developSystem baseline regression)
- scripts/ extract-all.mjs (从 jnpf-web 源码生成 schema) + seed-tds-baseline.ts
- doc/  architecture/plan/api/extractors/baseline/RESUME/help-system + v0.6/v0.7 changelog
- .claude/skills/dacli-ts/  Claude 集成 skill (SKILL.md + 5 references + 7 examples + 3 baseline)
- CLAUDE.md (项目说明) + README.md + prompt.md (开发任务说明书)
- 配置文件: package.json/lock, tsconfig, vitest.config, playwright.config
This commit is contained in:
ssw committed 2026-06-12 18:26:39 +08:00
commit c98ad4f425
93 files changed
+12718

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env node
/**
* cli.ts — dacli TS 版入口
*
* 调用: `npx tsx src/cli.ts <command>` 或 `node --import tsx src/cli.ts <command>`
*
* 设计: 嵌套子命令 (form/menu/dm/dict/workflow/doc/apis 父命令 + 子命令)
* AI 友好: 每个命令支持 --ai-help / --example / --source
*/
import { Command } from 'commander'
import { buildLoginCommand } from './commands/login.ts'
import { buildStatusCommand } from './commands/status.ts'
import { buildSwitchAppCommand } from './commands/switch-app.ts'
import { buildFormCommand } from './commands/form/index.ts'
import { buildDmCommand } from './commands/dm/index.ts'
import { buildDictCommand } from './commands/dict/index.ts'
import { buildMenuCommand } from './commands/menu/index.ts'
import { buildDiCommand } from './commands/di/index.ts'
import { buildWorkflowCommand } from './commands/workflow/index.ts'
import { buildDocCommand } from './commands/doc/index.ts'
import { buildApisCommand } from './commands/apis/index.ts'
import { maybeInterceptAiHelp } from './core/help.ts'
import { log } from './core/log.ts'
import { DacliError } from './core/types.ts'
const VERSION = '0.1.0'
const program = new Command()
.name('dacli')
.description('dacli (TS 版) — AI 驱动的 JNPF CLI. 0 差错 baseline 复刻.')
.version(VERSION)
.showHelpAfterError(true)
// ----- 顶层命令 -----
program.addCommand(buildLoginCommand())
program.addCommand(buildStatusCommand())
program.addCommand(buildSwitchAppCommand())
// ----- 嵌套父命令 -----
program.addCommand(buildFormCommand())
program.addCommand(buildDmCommand())
program.addCommand(buildDictCommand())
program.addCommand(buildMenuCommand())
program.addCommand(buildDiCommand())
program.addCommand(buildWorkflowCommand())
program.addCommand(buildDocCommand())
program.addCommand(buildApisCommand())
// ----- main -----
// AI flag 拦截 (在 parse 之前, 避免 requiredOption 校验失败)
if (maybeInterceptAiHelp(program)) {
// 已 exit
}
program.parseAsync(process.argv).catch((err: unknown) => {
if (err instanceof DacliError) {
log.error(`${err.message}`)
if (err.raw && process.env.DACLI_DEBUG === '1') log.dim(err.raw)
process.exit(1)
}
log.error(`${(err as Error).message}`)
if (process.env.DACLI_DEBUG === '1') console.error(err)
process.exit(1)
})
+11
View File
@@ -0,0 +1,11 @@
/**
* commands/apis/index.ts — apis 父命令 (JNPF OpenAPI 查询)
*/
import { Command } from 'commander'
import { buildApisListCommand } from './list.ts'
export function buildApisCommand(): Command {
const cmd = new Command('apis').description('JNPF 平台 API 查 (OpenAPI)')
cmd.addCommand(buildApisListCommand())
return cmd
}
+82
View File
@@ -0,0 +1,82 @@
/**
* commands/apis/list.ts — JNPF OpenAPI 接口列表
*
* API: GET /v3/api-docs (SpringDoc) → 解析 paths
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts { tag?: string; method?: string; keyword?: string; json?: boolean }
interface OpenApiPath {
[method: string]: {
summary?: string
tags?: string[]
operationId?: string
parameters?: unknown[]
}
}
interface OpenApiDoc {
paths: Record<string, OpenApiPath>
tags?: { name: string; description?: string }[]
}
export function buildApisListCommand(): Command {
const cmd = new Command('list')
.description('列 JNPF 平台所有 API (从 /v3/api-docs 拉取)')
.option('--tag <t>', '按 tag 过滤 (e.g. visualdev / system / workflow)')
.option('--method <m>', '按 HTTP method 过滤 (GET/POST/...)')
.option('--keyword <k>', '按 path 或 summary 搜索')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
// /v3/api-docs 是 SpringDoc 全局, 绕过 /api 前缀; 同时 nginx 经常不代理这路径,
// 优先尝试 backend (127.0.0.1:30000) 然后再试 baseUrl 去 /api
const host = c.baseUrl.replace(/\/api$/, '').replace(/\/+$/, '')
const candidates = [
host.replace(/^http:\/\/[^/]+/, 'http://127.0.0.1:30000') + '/v3/api-docs',
host + '/v3/api-docs',
]
let res: Response | null = null
let lastErr = ''
for (const url of candidates) {
log.debug('GET', url)
try {
const r = await fetch(url, { headers: { Authorization: c.token } })
if (r.ok) { res = r; break }
lastErr = `HTTP ${r.status}`
} catch (e) { lastErr = (e as Error).message }
}
if (!res) { log.error(`apis list 失败: ${lastErr}`); process.exit(1) }
const doc = (await res.json()) as OpenApiDoc
const rows: { method: string; path: string; summary: string; tags: string[] }[] = []
for (const [path, methods] of Object.entries(doc.paths || {})) {
for (const [method, op] of Object.entries(methods)) {
if (opts.method && method.toUpperCase() !== opts.method.toUpperCase()) continue
if (opts.tag && !(op.tags || []).includes(opts.tag)) continue
if (opts.keyword && !`${path} ${op.summary || ''}`.toLowerCase().includes(opts.keyword.toLowerCase())) continue
rows.push({ method: method.toUpperCase(), path, summary: op.summary || '', tags: op.tags || [] })
}
}
if (opts.json) { printJson(rows); return }
log.info(`共 ${rows.length} 个 API`)
console.log('METHOD PATH TAGS')
console.log('-'.repeat(100))
for (const r of rows) {
console.log(`${r.method.padEnd(7)} ${r.path.padEnd(60)} ${r.tags.join(',')}`)
}
})
installAiHelpHook(cmd, {
purpose: '列 JNPF 平台全量 API. AI 干活前先 --tag 查相关业务接口.',
required: {},
optional: { '--tag': '按 tag 过滤', '--method': 'GET/POST', '--keyword': '搜索' },
example: ['dacli apis list --tag=visualdev', 'dacli apis list --keyword=用户'],
source: { api: 'GET /v3/api-docs (SpringDoc OpenAPI)' },
notes: ['镜像 Java dacli 行为, 但 TS 版不写本地缓存, 每次现拉 (v1 简化)'],
})
return cmd
}
+11
View File
@@ -0,0 +1,11 @@
/**
* commands/di/index.ts — di 父命令 (数据接口)
*/
import { Command } from 'commander'
import { buildDiListCommand } from './list.ts'
export function buildDiCommand(): Command {
const cmd = new Command('di').description('数据接口 (弹窗选择/下拉补全/关联表单)')
cmd.addCommand(buildDiListCommand())
return cmd
}
+45
View File
@@ -0,0 +1,45 @@
/**
* commands/di/list.ts — 数据接口列表
*
* API: GET /api/system/DataInterface
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts { json?: boolean; keyword?: string; currentPage?: string; pageSize?: string }
export function buildDiListCommand(): Command {
const cmd = new Command('list')
.description('数据接口列表 (form select 弹窗常用)')
.option('--keyword <k>', '搜索')
.option('--currentPage <p>', '页码', '1')
.option('--pageSize <s>', '每页', '50')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const r = await c.get<{ list?: { id: string; fullName: string; enCode: string; categoryId?: string }[] }>(
'/system/DataInterface',
{ keyword: opts.keyword, currentPage: opts.currentPage, pageSize: opts.pageSize },
)
if (r.code !== 200) { log.error(`di list 失败: ${r.msg}`); process.exit(1) }
const list = r.data?.list || []
if (opts.json) { printJson(r.data); return }
log.info(`共 ${list.length} 个数据接口`)
console.log('ID FULL_NAME ENCODE')
console.log('-'.repeat(80))
for (const d of list) {
console.log(`${String(d.id).padEnd(36)}${(d.fullName || '').padEnd(22)}${d.enCode || ''}`)
}
})
installAiHelpHook(cmd, {
purpose: '列出所有数据接口 (弹窗选择/下拉补全/关联表单用).',
required: {},
optional: { '--keyword': '搜索' },
example: 'dacli di list',
source: { api: 'GET /api/system/DataInterface' },
})
return cmd
}
+51
View File
@@ -0,0 +1,51 @@
/**
* commands/dict/data-list.ts — 字典数据列表
*
* API: GET /api/system/DictionaryData/{typeId}/Data 或 /All
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts {
typeId?: string
all?: boolean
json?: boolean
}
export function buildDictDataListCommand(): Command {
const cmd = new Command('data-list')
.description('字典数据列表 (按 typeId 或全部)')
.option('--typeId <id>', '字典类型 id (不传则返回全部)')
.option('--all', '等价于不传 typeId 调 /All', false)
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
let path: string
if (opts.all || !opts.typeId) {
path = '/system/DictionaryData/All'
} else {
path = `/system/DictionaryData/${opts.typeId}/Data`
}
const r = await c.get<unknown>(path)
if (r.code !== 200) { log.error(`dict data-list 失败: ${r.msg}`); process.exit(1) }
if (opts.json) { printJson(r.data); return }
const list = (Array.isArray(r.data) ? r.data : (r.data as { list?: unknown[] })?.list) || []
log.info(`${path} 共 ${list.length} 条`)
console.log('ENCODE FULL_NAME SORT')
console.log('-'.repeat(60))
for (const d of list as Record<string, unknown>[]) {
console.log(`${String(d.enCode || d.id || '').padEnd(21)}${String(d.fullName || '').padEnd(22)}${d.sortCode || ''}`)
}
})
installAiHelpHook(cmd, {
purpose: '看字典数据. --typeId 看单类型, 不传 --all 拿全部.',
required: {},
optional: { '--typeId': '字典类型 id', '--all': '拿全部字典' },
example: 'dacli dict data-list --typeId=<id>',
source: { api: 'GET /api/system/DictionaryData/{typeId}/Data 或 /All' },
})
return cmd
}
+13
View File
@@ -0,0 +1,13 @@
/**
* commands/dict/index.ts — dict 父命令
*/
import { Command } from 'commander'
import { buildDictTypeListCommand } from './type-list.ts'
import { buildDictDataListCommand } from './data-list.ts'
export function buildDictCommand(): Command {
const cmd = new Command('dict').description('字典管理 (类型 + 数据)')
cmd.addCommand(buildDictTypeListCommand())
cmd.addCommand(buildDictDataListCommand())
return cmd
}
+40
View File
@@ -0,0 +1,40 @@
/**
* commands/dict/type-list.ts — 字典类型列表
*
* API: GET /api/system/DictionaryType
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts { json?: boolean; keyword?: string }
export function buildDictTypeListCommand(): Command {
const cmd = new Command('type-list')
.description('字典类型列表')
.option('--keyword <k>', '按编码/名称搜索')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const r = await c.get<unknown>('/system/DictionaryType', { keyword: opts.keyword })
if (r.code !== 200) { log.error(`dict type-list 失败: ${r.msg}`); process.exit(1) }
if (opts.json) { printJson(r.data); return }
const list = (r.data as { list?: Record<string, unknown>[] })?.list || []
log.info(`共 ${list.length} 个字典类型`)
console.log('ID ENCODE FULL_NAME')
console.log('-'.repeat(80))
for (const t of list) {
console.log(`${String(t.id || '').padEnd(36)}${String(t.enCode || '').padEnd(21)}${t.fullName || ''}`)
}
})
installAiHelpHook(cmd, {
purpose: '列出所有字典类型 (e.g. 性别/状态/教育程度 等下拉字典).',
required: {},
optional: { '--keyword': '搜索关键字' },
example: 'dacli dict type-list',
source: { api: 'GET /api/system/DictionaryType' },
})
return cmd
}
+91
View File
@@ -0,0 +1,91 @@
/**
* commands/dm/create.ts — 创建物理表
*
* API: POST /api/system/DataModel/{linkId}/Table
*
* 注意: tables[].fields[] 必须含 autoIncrement/identity/columnName 等
* 见 prompt §6.3 "Database exception"
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface CreateOpts {
table: string
tableName: string
dbLinkId?: string
fields: string
json?: boolean
}
export function buildDmCreateCommand(): Command {
const cmd = new Command('create')
.description('在指定业务库建物理表 (fields 必传 JSON)')
.requiredOption('--table <name>', '表名 (snake_case)')
.requiredOption('--tableName <cn>', '表中文名')
.requiredOption('--fields <json>', '字段定义 JSON 数组')
.option('--dbLinkId <id>', '业务库 id (默认从 token.dbLinkId)')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: CreateOpts) => {
const c = await JnpfClient.fromToken()
const dbLinkId = opts.dbLinkId || c.dbLinkId || '0'
const userFields = JSON.parse(opts.fields) as Record<string, unknown>[]
// 强制补全 schema 必填项 (autoIncrement/identity/columnName/index/primaryKey)
const fields = userFields.map((f) => ({
autoIncrement: 0,
identity: 0,
primaryKey: 0,
index: '0',
columnName: f.field,
...f,
}))
// v10.6+ JNPF runtime 要求 9 系统列 (硬编码 SQL 引用) + 复合主键
const sysCols = [
{ field: 'f_id', fieldName: '主键', dataType: 'varchar', dataLength: '50', primaryKey: 1, allowNull: 0, autoIncrement: 0, identity: 0, columnName: 'f_id', index: '0' },
{ field: 'f_tenant_id', fieldName: '租户id', dataType: 'varchar', dataLength: '50', primaryKey: 1, allowNull: 0, autoIncrement: 0, identity: 0, columnName: 'f_tenant_id', index: '0' },
{ field: 'f_flow_task_id', fieldName: '流程任务ID', dataType: 'varchar', dataLength: '50', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_flow_task_id', index: '0' },
{ field: 'f_flow_id', fieldName: '流程ID', dataType: 'varchar', dataLength: '50', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_flow_id', index: '0' },
{ field: 'f_flow_state', fieldName: '流程状态', dataType: 'int', dataLength: '0', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_flow_state', index: '0' },
{ field: 'f_sort_code', fieldName: '排序', dataType: 'bigint', dataLength: '0', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_sort_code', index: '0' },
{ field: 'f_create_user', fieldName: '创建人', dataType: 'varchar', dataLength: '50', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_create_user', index: '0' },
{ field: 'f_create_time', fieldName: '创建时间', dataType: 'datetime', dataLength: '0', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_create_time', index: '0' },
{ field: 'f_modify_user', fieldName: '修改人', dataType: 'varchar', dataLength: '50', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_modify_user', index: '0' },
{ field: 'f_modify_time', fieldName: '修改时间', dataType: 'datetime', dataLength: '0', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_modify_time', index: '0' },
{ field: 'f_description', fieldName: '描述', dataType: 'text', dataLength: '0', primaryKey: 0, allowNull: 1, autoIncrement: 0, identity: 0, columnName: 'f_description', index: '0' },
]
const allFields = [...fields, ...sysCols]
// JNPF dmpost body 结构: { tableInfo:{...}, tableFieldList:[...] }
const body = {
tableInfo: {
table: opts.table,
tableName: opts.tableName,
newTable: opts.table,
primaryKeyPolicy: 1,
logicalDelete: false,
concurrencyLock: false,
},
tableFieldList: allFields,
}
log.info(`POST /system/DataModel/${dbLinkId}/Table table=${opts.table} fields=${allFields.length} (含9系统列)`)
const r = await c.postJson<{ table?: string }>(`/system/DataModel/${dbLinkId}/Table`, body)
if (r.code !== 200) {
log.error(`建表失败 (code=${r.code}): ${r.msg}`)
if (opts.json) printJson(r)
process.exit(1)
}
log.ok(`建表成功: ${opts.table}`)
if (opts.json) printJson(r.data)
})
installAiHelpHook(cmd, {
purpose: '在指定业务库建物理表. fields JSON 必含 field/fieldName/dataType/dataLength.',
required: { '--table': '表名', '--tableName': '中文名', '--fields': '字段 JSON' },
optional: { '--dbLinkId': '业务库 id' },
example: `dacli dm create --table=test_table --tableName="测试表" --fields='[{"field":"f_name","fieldName":"名称","dataType":"varchar","dataLength":"100","allowNull":0}]'`,
source: { api: 'POST /api/system/DataModel/{dbLinkId}/Table' },
notes: ['autoIncrement/identity/columnName 已自动补全', '建表前确认 dbLinkId 对应业务库'],
})
return cmd
}
+51
View File
@@ -0,0 +1,51 @@
/**
* commands/dm/drop.ts — 删除物理表
*
* API: DELETE /api/system/DataModel/{linkId}/Table/{table}
*
* ⚠️ 危险操作, 表数据不可恢复. 真实执行需双重人工确认 (TODO: 加 TTY 拦截)
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
interface DropOpts {
table: string
dbLinkId?: string
yes?: boolean
}
export function buildDmDropCommand(): Command {
const cmd = new Command('drop')
.description('删除物理表 (⚠️ 不可恢复)')
.requiredOption('--table <name>', '表名')
.option('--dbLinkId <id>', '业务库 id')
.option('--yes', '跳过确认', false)
.action(async (opts: DropOpts) => {
if (!opts.yes) {
log.warn(`即将删除表: ${opts.table}`)
log.warn('传 --yes 确认 (数据不可恢复)')
process.exit(2)
}
const c = await JnpfClient.fromToken()
const dbLinkId = opts.dbLinkId || c.dbLinkId || '0'
log.info(`DELETE /system/DataModel/${dbLinkId}/Table/${opts.table}`)
const r = await c.del(`/system/DataModel/${dbLinkId}/Table/${opts.table}`)
if (r.code !== 200) {
log.error(`删表失败 (code=${r.code}): ${r.msg}`)
process.exit(1)
}
log.ok(`已删除: ${opts.table}`)
})
installAiHelpHook(cmd, {
purpose: '删除物理表. ⚠️ 不可恢复.',
required: { '--table': '表名', '--yes': '必须传 --yes 跳过确认' },
optional: { '--dbLinkId': '业务库 id' },
example: 'dacli dm drop --table=test_table --yes',
source: { api: 'DELETE /api/system/DataModel/{dbLinkId}/Table/{table}' },
notes: ['生产环境务必先用 dacli initapp --backup 备份'],
})
return cmd
}
+66
View File
@@ -0,0 +1,66 @@
/**
* commands/dm/fields.ts — 看表字段
*
* API: GET /api/system/DataModel/{linkId}/Tables/{table}/Fields?field=*
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface FieldsOpts {
table: string
dbLinkId?: string
json?: boolean
}
export function buildDmFieldsCommand(): Command {
const cmd = new Command('fields')
.description('看物理表的所有字段')
.requiredOption('--table <name>', '表名')
.option('--dbLinkId <id>', '业务库 id')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: FieldsOpts) => {
const c = await JnpfClient.fromToken()
const dbLinkId = opts.dbLinkId || c.dbLinkId || '0'
const r = await c.get<{ fields?: Record<string, unknown>[] } | Record<string, unknown>>(
`/system/DataModel/${dbLinkId}/Tables/${opts.table}/Fields`,
{ field: '*' },
)
if (r.code !== 200) {
log.error(`查字段失败 (code=${r.code}): ${r.msg}`)
process.exit(1)
}
if (opts.json) {
printJson(r.data)
return
}
// 兼容 data 是数组 / { list: [...] } (后端实际) / { fields: [...] }
const dataObj = r.data as Record<string, unknown> | unknown[] | null
const arr = Array.isArray(dataObj)
? dataObj
: ((dataObj as { list?: unknown[]; fields?: unknown[] })?.list ||
(dataObj as { fields?: unknown[] })?.fields ||
[])
log.info(`表 ${opts.table} 字段数=${arr.length}`)
console.log('FIELD TYPE LENGTH NULL PK')
console.log('-'.repeat(60))
for (const f of arr as Array<Record<string, unknown>>) {
const field = String(f.field || f.columnName || '').padEnd(20)
const type = String(f.dataType || '').padEnd(14)
const len = String(f.dataLength || '').padEnd(7)
const nullable = f.allowNull === 0 || f.allowNull === '0' ? 'NO' : 'YES'
const pk = f.primaryKey === 1 || f.primaryKey === '1' ? 'PK' : ''
console.log(`${field}${type}${len}${nullable.padEnd(5)}${pk}`)
}
})
installAiHelpHook(cmd, {
purpose: '查指定物理表的所有字段定义.',
required: { '--table': '表名' },
optional: { '--dbLinkId': '业务库 id' },
example: 'dacli dm fields --table=leave',
source: { api: 'GET /api/system/DataModel/{dbLinkId}/Tables/{table}/Fields' },
})
return cmd
}
+25
View File
@@ -0,0 +1,25 @@
/**
* commands/dm/index.ts — dm 父命令
*
* 数据模型 CRUD (JNPF 业务库/主库物理表管理)
*
* 子命令:
* list 列表
* create 建表
* drop 删表
* fields 看字段
*/
import { Command } from 'commander'
import { buildDmListCommand } from './list.ts'
import { buildDmCreateCommand } from './create.ts'
import { buildDmDropCommand } from './drop.ts'
import { buildDmFieldsCommand } from './fields.ts'
export function buildDmCommand(): Command {
const cmd = new Command('dm').description('数据模型 (业务库物理表) 管理')
cmd.addCommand(buildDmListCommand())
cmd.addCommand(buildDmCreateCommand())
cmd.addCommand(buildDmDropCommand())
cmd.addCommand(buildDmFieldsCommand())
return cmd
}
+59
View File
@@ -0,0 +1,59 @@
/**
* commands/dm/list.ts — 列出数据模型表
*
* API: GET /api/system/DataModel/{linkId}/Tables?currentPage=&pageSize=&keyword=
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface ListOpts {
dbLinkId?: string
keyword?: string
page?: string
pageSize?: string
json?: boolean
}
export function buildDmListCommand(): Command {
const cmd = new Command('list')
.description('列出数据模型 (业务库/主库表)')
.option('--dbLinkId <id>', '业务库 id (默认从 token.dbLinkId)')
.option('--keyword <k>', '按表名模糊搜索')
.option('--page <p>', '页码', '1')
.option('--pageSize <s>', '每页条数', '50')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: ListOpts) => {
const c = await JnpfClient.fromToken()
const dbLinkId = opts.dbLinkId || c.dbLinkId || '0'
const r = await c.get<{ list: { table: string; tableName: string; primaryKeyPolicy?: number }[] }>(
`/system/DataModel/${dbLinkId}/Tables`,
{ currentPage: opts.page, pageSize: opts.pageSize, keyword: opts.keyword },
)
if (r.code !== 200) {
log.error(`dm list 失败 (code=${r.code}): ${r.msg}`)
process.exit(1)
}
const list = r.data?.list || []
if (opts.json) {
printJson(r.data)
return
}
log.info(`dbLinkId=${dbLinkId} 共 ${list.length} 张表`)
console.log('TABLE TABLE_NAME(中文)')
console.log('-'.repeat(60))
for (const t of list) {
console.log(`${t.table.padEnd(30)}${t.tableName || ''}`)
}
})
installAiHelpHook(cmd, {
purpose: '列出指定业务库的所有数据模型表. dbLinkId=0 是主库 (平台库).',
required: {},
optional: { '--dbLinkId': '业务库 id', '--keyword': '表名搜索', '--page': '页码', '--pageSize': '每页条数' },
example: 'dacli dm list',
source: { api: 'GET /api/system/DataModel/{dbLinkId}/Tables' },
})
return cmd
}
+11
View File
@@ -0,0 +1,11 @@
/**
* commands/doc/index.ts — doc 父命令 (HTML 文档)
*/
import { Command } from 'commander'
import { buildDocListCommand } from './list.ts'
export function buildDocCommand(): Command {
const cmd = new Command('doc').description('HTML 文档 (从 docs/{app}/ 扫描)')
cmd.addCommand(buildDocListCommand())
return cmd
}
+57
View File
@@ -0,0 +1,57 @@
/**
* commands/doc/list.ts — 列出 HTML 文档 (来自 docs/{app}/)
*
* v1 简化版: 仅扫描 .claude/skills/dacli-ts/examples/docs/ 和 docs/{app_code}/
* 镜像 Java dacli 的 HTML 缓存子命令, 但不写 SQLite (避免依赖)
*/
import { Command } from 'commander'
import { readdirSync, statSync, existsSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts { dir?: string; json?: boolean }
interface DocFile { path: string; size: number; mtime: Date }
function walkHtml(dir: string, base = ''): DocFile[] {
if (!existsSync(dir)) return []
const out: DocFile[] = []
for (const name of readdirSync(dir)) {
const full = join(dir, name)
const rel = base ? `${base}/${name}` : name
const s = statSync(full)
if (s.isDirectory()) out.push(...walkHtml(full, rel))
else if (name.endsWith('.html') || name.endsWith('.htm')) {
out.push({ path: rel, size: s.size, mtime: s.mtime })
}
}
return out.sort((a, b) => a.path.localeCompare(b.path))
}
export function buildDocListCommand(): Command {
const cmd = new Command('list')
.description('列 HTML 文档 (从 docs/{app_code}/ 扫描)')
.option('--dir <d>', '扫描目录 (默认 docs/)', 'docs')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const target = resolve(process.cwd(), opts.dir || 'docs')
const files = walkHtml(target)
if (opts.json) { printJson(files); return }
log.info(`目录 ${target} 共 ${files.length} 个 HTML 文档`)
console.log('PATH SIZE MTIME')
console.log('-'.repeat(80))
for (const f of files) {
console.log(`${f.path.padEnd(50)}${String(f.size).padEnd(7)}${f.mtime.toISOString().slice(0, 16)}`)
}
})
installAiHelpHook(cmd, {
purpose: '列 HTML 文档, AI 上下文恢复时先看 list 再 cat 关键 section.',
required: {},
optional: { '--dir': '扫描目录' },
example: ['dacli doc list', 'dacli doc list --dir=docs/tds'],
notes: ['镜像 Java dacli doc 行为, v1 不写本地缓存 (直接读文件系统)'],
})
return cmd
}
+75
View File
@@ -0,0 +1,75 @@
/**
* commands/form/clone.ts — 克隆表单 (export + import 一步到位)
*
* AI 黄金法则: 99% 的"建新表单"应该 clone 再改
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
import type { FormDetail } from '../../core/types.ts'
type Cloneable = Record<string, unknown> & Partial<FormDetail>
interface CloneOpts {
newEnCode?: string
newFullName?: string
newDbLinkId?: string
release?: boolean
}
export function buildFormCloneCommand(): Command {
const cmd = new Command('clone')
.description('克隆表单 (export + import 一步搞定)')
.argument('<id>', '源表单 id')
.option('--newEnCode <e>', '新 enCode (默认原 +_clone)')
.option('--newFullName <n>', '新中文名 (默认原 +_克隆)')
.option('--newDbLinkId <id>', '新业务库 id (跨应用克隆必传)')
.option('--release', '克隆后立刻发布', false)
.action(async (id: string, opts: CloneOpts) => {
const c = await JnpfClient.fromToken()
const r = await c.get<FormDetail>(`/visualdev/Base/${id}`)
const src = c.ok(r) as Cloneable
delete src.id
delete src.creatorTime
delete src.creatorUserId
delete src.systemId
src.state = 0
src.enCode = opts.newEnCode || `${src.enCode}_clone`
if (opts.newFullName) src.fullName = opts.newFullName
else src.fullName = `${src.fullName}_克隆`
if (opts.newDbLinkId) src.dbLinkId = opts.newDbLinkId
const rr = await c.postJson('/visualdev/Base', src)
if (rr.code !== 200) {
log.error(`克隆失败 code=${rr.code}: ${rr.msg}`)
process.exit(1)
}
const listR = await c.get<{ list: { id: string; enCode: string }[] }>('/visualdev/Base/list', {
keyword: src.enCode,
})
const newId = listR.data?.list.find((f) => f.enCode === src.enCode)?.id || '(unknown)'
log.ok(`克隆成功 ${id} → ${newId} enCode=${src.enCode}`)
if (opts.release && src.type !== 4 && newId !== '(unknown)') {
const r3 = await c.postJson(`/visualdev/Base/${newId}/Actions/Release`, {})
if (r3.code === 200) log.ok('发布成功')
else log.warn(`发布失败 code=${r3.code}: ${r3.msg}`)
}
})
installAiHelpHook(cmd, {
purpose: 'AI 黄金法则: 99% 的新表单应 clone 再改, 不要从零搭. 这是 dacli 最常用的命令',
required: { '<id>': '源表单 id' },
optional: {
'--newEnCode': '新 enCode',
'--newFullName': '新中文名',
'--newDbLinkId': '跨应用克隆必传',
'--release': '克隆后立刻发布 (type=4 自动跳过)',
},
example: 'dacli form clone 12345 --newEnCode=leaveV2 --release',
source: { api: 'GET /visualdev/Base/:id + POST /visualdev/Base' },
})
return cmd
}
+154
View File
@@ -0,0 +1,154 @@
/**
* commands/form/create.ts — 创建表单
*
* 默认场景 (AI 友好):
* - type=4 (视图, 无物理表) + webType=1 → 99% 不会 "Database exception"
* - 完整字段走 --fields JSON
*
* 提示: clone 优先, 这是兜底
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface CreateOpts {
fullName: string
enCode: string
type?: string
webType?: string
category?: string
dbLinkId?: string
fields?: string
tables?: string
enableFlow?: string
flowId?: string
autoRelease?: boolean
json?: boolean
}
export function buildFormCreateCommand(): Command {
const cmd = new Command('create')
.description('创建表单 (默认 type=4 视图 + webType=1, 兜底不会 Database exception)')
.requiredOption('--fullName <n>', '中文名')
.requiredOption('--enCode <e>', '英文编码 (snake/camelCase)')
.option('--type <t>', '1=自定义 2=系统 3=接口 4=视图', '4')
.option('--webType <w>', '1=仅表单 2=表单+列表 3=树+表单 4=数据视图', '1')
.option('--category <c>', '分类 id (form list 看真实值)')
.option('--dbLinkId <id>', 'db link id (type≠4 时必传, 默认从 token.dbLinkId)')
.option('--fields <json>', 'formData.fields JSON 数组')
.option('--tables <json>', 'tables JSON 数组 (type=1/2 必传)')
.option('--enableFlow <0|1>', '是否绑工作流', '0')
.option('--flowId <id>', '工作流 id (enableFlow=1 时必传)')
.option('--autoRelease', '建完立刻发布 (type=4 自动跳过)', false)
.option('--json', '原始 JSON 输出', false)
.action(async (opts: CreateOpts) => {
const c = await JnpfClient.fromToken()
const type = Number(opts.type)
const webType = Number(opts.webType)
const dbLinkId = opts.dbLinkId || c.dbLinkId || '0'
const formData = {
formRef: 'formRef',
formModel: 'dataForm',
fields: opts.fields ? JSON.parse(opts.fields) : [],
tableName: opts.enCode,
}
const columnDataObj = {
columnOptions: [],
searchList: [],
formData: {},
tableConfig: { border: true, stripe: false, size: 'default', showRadio: false, showRowNumber: true },
relationForm: { ' popupTable': '', columnOptions: [], searchForms: [] },
}
const tables = opts.tables
? JSON.parse(opts.tables)
: type === 4
? []
: [
{
table: opts.enCode,
typeId: '1',
comment: '主表',
fields: [
{ dataType: 'varchar', field: 'f_id', fieldName: '主键', primaryKey: 1 },
{ dataType: 'varchar', field: 'f_tenant_id', fieldName: '租户id', primaryKey: 1 },
],
},
]
const body: Record<string, unknown> = {
fullName: opts.fullName,
enCode: opts.enCode,
type,
webType: String(webType),
category: opts.category || null,
description: 'created by dacli (TS)',
dbLinkId,
enableFlow: Number(opts.enableFlow || '0'),
flowId: opts.flowId || '',
// 关键: formData/columnData/appColumnData/tables 都是字符串!
formData: JSON.stringify(formData),
columnData: JSON.stringify(columnDataObj),
appColumnData: JSON.stringify(columnDataObj),
tables: JSON.stringify(tables),
state: 0,
sortCode: 0,
}
log.info(`POST /visualdev/Base ${opts.enCode} type=${type} webType=${webType} dbLinkId=${dbLinkId}`)
const r = await c.postJson<unknown>('/visualdev/Base', body)
if (r.code !== 200) {
log.error(`创建失败 (code=${r.code}): ${r.msg}`)
if (opts.json) printJson(r)
process.exit(1)
}
// 拉 id (响应通常不回 id, 反查 list)
const listR = await c.get<{ list: { id: string; enCode: string }[] }>('/visualdev/Base/list', {
keyword: opts.enCode,
})
const newForm = listR.data?.list.find((f) => f.enCode === opts.enCode)
const newId = newForm?.id || '(unknown)'
log.ok(`创建成功: id=${newId} enCode=${opts.enCode}`)
if (opts.autoRelease && type !== 4 && newId !== '(unknown)') {
log.info(`发布: POST /visualdev/Base/${newId}/Actions/Release (v0.7 修)`)
const rr = await c.postJson(`/visualdev/Base/${newId}/Actions/Release`, {})
if (rr.code === 200) log.ok('发布成功 (state=1)')
else log.warn(`发布失败 (code=${rr.code}): ${rr.msg}`)
} else if (opts.autoRelease && type === 4) {
log.warn('type=4 视图自动跳过 release (会 400)')
}
if (opts.json) printJson({ id: newId, enCode: opts.enCode, type, webType })
})
installAiHelpHook(cmd, {
purpose: '创建表单. 默认 type=4 (视图) 兜底, 不会 Database exception. 业务建议 clone',
required: { '--fullName': '中文名', '--enCode': '英文编码' },
optional: {
'--type': '1/2/3/4 (默认 4)',
'--webType': '1/2/3/4 (默认 1)',
'--category': '分类 id',
'--dbLinkId': '业务库 id (type≠4 时必传)',
'--fields': 'formData.fields JSON',
'--tables': 'tables JSON (type=1/2)',
'--enableFlow': '0|1',
'--flowId': '工作流 id',
'--autoRelease': '建完立刻发布 (type=4 自动跳过)',
},
example: [
'dacli form create --fullName="POC 视图" --enCode=pocView',
'dacli form create --fullName="请假" --enCode=leave --type=1 --webType=2 --dbLinkId=664... --tables=\'[{"table":"leave","tableName":"请假"}]\' --fields=\'[...]\' --autoRelease',
],
source: { web: 'web/.../formDesign/Form.vue:444-465', api: 'POST /api/visualdev/Base' },
notes: [
'type=4 视图最稳, 不动物理表',
'AI 黄金法则: 99% 应先 clone 再改',
'autoRelease 对 type=4 自动跳过 (release 会 400)',
],
})
return cmd
}
+37
View File
@@ -0,0 +1,37 @@
/**
* commands/form/delete.ts — 删表单
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
export function buildFormDeleteCommand(): Command {
const cmd = new Command('delete')
.description('删除表单')
.argument('<id>', '表单 id')
.option('--yes', '跳过确认', false)
.action(async (id: string, opts: { yes?: boolean }) => {
if (!opts.yes && process.stdin.isTTY) {
log.warn(`确认删除 id=${id}? 加 --yes 跳过提示`)
process.exit(1)
}
const c = await JnpfClient.fromToken()
const r = await c.del(`/visualdev/Base/${id}`)
if (r.code === 200) log.ok(`已删 id=${id}`)
else {
log.error(`删除失败 code=${r.code}: ${r.msg}`)
process.exit(1)
}
})
installAiHelpHook(cmd, {
purpose: '删除表单. 不可恢复, 加 --yes 跳过确认',
required: { '<id>': '表单 id' },
optional: { '--yes': '跳过确认' },
example: 'dacli form delete 1234567890 --yes',
source: { api: 'DELETE /api/visualdev/Base/:id' },
})
return cmd
}
+111
View File
@@ -0,0 +1,111 @@
/**
* commands/form/export.ts — 导出表单 JSON
*
* v0.7: 同时拉物理表 schema 存到 `_physicalSchema`,
* 解 #15 (web Form.vue tables[].fields 是 DB 实时查的, 不在 form JSON 里).
* 配合 import.ts 的 --autoTable 在目标库重建物理表.
*
* 关键: web 端 createDataModel 是单独走「数据建模」入口, form 设计器只引用表名;
* 迁移时若不带物理 schema 出来, import 后浏览器报 "该表单已删除".
*/
import { writeFileSync } from 'node:fs'
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import type { FormDetail } from '../../core/types.ts'
interface PhysicalSchemaEntry {
table: string
tableName?: string
typeId?: string
fields: Record<string, unknown>[]
}
interface ExportedForm extends FormDetail {
_physicalSchema?: PhysicalSchemaEntry[]
_exportedAt?: string
}
export function buildFormExportCommand(): Command {
const cmd = new Command('export')
.description('导出表单完整 schema 到文件 (v0.7 同时带物理表 schema, 解 #15)')
.argument('<id>', '表单 id')
.option('--out <path>', '输出文件路径 (默认 ./<enCode>.json)')
.option('--no-physical', '不带物理表 schema (默认会带, 兼容旧版导出)')
.action(async (id: string, opts: { out?: string; physical?: boolean }) => {
const c = await JnpfClient.fromToken()
const r = await c.get<FormDetail>(`/visualdev/Base/${id}`)
const data = c.ok(r) as ExportedForm
// v0.7: 拉物理表 schema (除非 --no-physical)
if (opts.physical !== false) {
try {
// FormDetail.tables 类型偏宽, 后端实际返 JSON string, 强转
const tables = data.tables
? (JSON.parse(typeof data.tables === 'string' ? data.tables : JSON.stringify(data.tables)) as Array<
Record<string, unknown>
>)
: []
const physical: PhysicalSchemaEntry[] = []
for (const t of tables) {
const tableName = String(t.table || '')
if (!tableName) continue
const dbLinkId = String(data.dbLinkId || '0')
try {
const fr = await c.get<{ fields?: Record<string, unknown>[] } | Record<string, unknown>[]>(
`/system/DataModel/${dbLinkId}/Tables/${tableName}/Fields`,
{ field: '*' },
)
if (fr.code === 200) {
const arr = Array.isArray(fr.data)
? fr.data
: (fr.data as { fields?: Record<string, unknown>[] })?.fields || []
physical.push({
table: tableName,
tableName: t.tableName as string | undefined,
typeId: t.typeId as string | undefined,
fields: arr,
})
log.debug(` ↳ 拉 ${tableName} 字段 ×${arr.length}`)
} else {
log.warn(` ↳ ${tableName} 字段查失败 code=${fr.code}: ${fr.msg} (跳过)`)
}
} catch (e) {
log.warn(` ↳ ${tableName} 字段查异常: ${(e as Error).message} (跳过)`)
}
}
if (physical.length) {
data._physicalSchema = physical
data._exportedAt = new Date().toISOString()
}
} catch (e) {
log.warn(`物理表 schema 解析失败 (跳过): ${(e as Error).message}`)
}
}
const path = opts.out || `./${data.enCode || id}.json`
writeFileSync(path, JSON.stringify(data, null, 2), 'utf-8')
const sizeKb = (JSON.stringify(data).length / 1024).toFixed(1)
const phyCount = data._physicalSchema?.length ?? 0
log.ok(`已导出 ${data.enCode} → ${path} (${sizeKb} KB, 含 ${phyCount} 张物理表 schema)`)
if (!opts.out) printJson({ id, enCode: data.enCode, path, physicalTables: phyCount })
})
installAiHelpHook(cmd, {
purpose: '导出表单完整 schema + 物理表 schema 到文件 (v0.7 解 #15). 用于 baseline 复刻 / 备份 / 跨应用迁移',
required: { '<id>': '源表单 id' },
optional: {
'--out': '输出路径, 默认 ./<enCode>.json',
'--no-physical': '不带物理表 schema (兼容旧导出格式)',
},
example: 'dacli form export 12345 --out=/tmp/leave.json',
source: { api: 'GET /api/visualdev/Base/:id + GET /api/system/DataModel/:linkId/Tables/:table/Fields' },
notes: [
'v0.7 默认带物理表 schema (_physicalSchema 字段), 配合 form import --autoTable 重建物理表',
'web/.../formDesign/Form.vue tables[].fields 是 DB 实时查的, 不在 form JSON 里, 所以必须单独拉',
],
})
return cmd
}
+254
View File
@@ -0,0 +1,254 @@
/**
* commands/form/import.ts — 导入表单 JSON
*
* v0.7: 加 --autoTable (默认 true) 解 #15.
* - 检测 _physicalSchema → 先在目标 dbLinkId 重建物理表
* - 重命名 tables[].table + formData[].tableName → 跟随新 enCode 避免重名
* - 然后 POST /visualdev/Base
*
* 顺序 (web 端是「先建表 → 再设计表单」, 我们 CLI 一气呵成):
* 1. read JSON
* 2. rewrite table names (避免目标库重名)
* 3. (autoTable) POST /system/DataModel/{dbLinkId}/Table × N
* 4. POST /visualdev/Base
* 5. (release) POST /visualdev/Base/{id}/Actions/Release (v0.7 修, 老 PUT /Actions/State 是错的)
*/
import { readFileSync } from 'node:fs'
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
interface ImportOpts {
enCode?: string
fullName?: string
dbLinkId?: string
table?: string
release?: boolean
autoTable?: boolean
json?: boolean
}
interface PhysicalSchemaEntry {
table: string
tableName?: string
typeId?: string
fields: Record<string, unknown>[]
}
interface ImportPayload {
id?: string
creatorTime?: unknown
creatorUserId?: unknown
systemId?: unknown
state?: number
enCode?: string
fullName?: string
dbLinkId?: string
type?: number
webType?: string | number
tables?: string
formData?: string
columnData?: string
appColumnData?: string
_physicalSchema?: PhysicalSchemaEntry[]
[k: string]: unknown
}
export function buildFormImportCommand(): Command {
const cmd = new Command('import')
.description('从 JSON 导入表单 (v0.7 默认 --autoTable 重建物理表, 解 #15)')
.argument('<file>', '表单 JSON 路径')
.option('--enCode <e>', '新 enCode (默认原值 + _clone)')
.option('--fullName <n>', '新 fullName (默认原值)')
.option('--dbLinkId <id>', '新业务库 id (默认 token.dbLinkId, 跨应用迁移强烈推荐传)')
.option('--table <name>', '新主表名 (默认 enCode 小写, 避免目标库重名)')
.option('--release', '导入后立刻发布', false)
.option('--autoTable', '导入前重建物理表 (默认 true, --no-autoTable 跳过)', true)
.option('--no-autoTable', '不重建物理表 (老 export 没 _physicalSchema 时)')
.action(async (file: string, opts: ImportOpts) => {
const c = await JnpfClient.fromToken()
const raw = JSON.parse(readFileSync(file, 'utf-8')) as ImportPayload
// 清掉冲突字段
delete raw.id
delete raw.creatorTime
delete raw.creatorUserId
delete raw.systemId
raw.state = 0
const newEnCode = opts.enCode || `${raw.enCode || 'unknown'}_clone`
raw.enCode = newEnCode
if (opts.fullName) raw.fullName = opts.fullName
const targetDbLinkId = opts.dbLinkId || c.dbLinkId || (raw.dbLinkId as string) || '0'
raw.dbLinkId = targetDbLinkId
// ---- v0.7: tables 重命名 (旧表名 → 新表名, 避免跨应用重名) ----
// 主表新名: --table 给, 或默认 enCode 小写
const newMainTable = (opts.table || newEnCode).toLowerCase()
let tableRenameMap: Record<string, string> = {}
let parsedTables: Array<Record<string, unknown>> = []
if (raw.tables) {
try {
parsedTables = JSON.parse(raw.tables) as Array<Record<string, unknown>>
} catch {
log.warn('tables JSON 解析失败, 跳过重命名')
}
// 找主表 (typeId=1), 第一个改成 newMainTable; 子表保留旧名 (但若 _physicalSchema 在, 也会建)
const mainIdx = parsedTables.findIndex((t) => String(t.typeId) === '1')
const effectiveMainIdx = mainIdx >= 0 ? mainIdx : 0
for (let i = 0; i < parsedTables.length; i++) {
const oldName = String(parsedTables[i].table || '')
const newName = i === effectiveMainIdx ? newMainTable : `${oldName}_${newEnCode}`.toLowerCase()
if (oldName && oldName !== newName) {
tableRenameMap[oldName] = newName
parsedTables[i].table = newName
// 子表的 relationTable 也跟着改
if (parsedTables[i].relationTable === oldName) parsedTables[i].relationTable = newName
}
}
// 反查: 其他表的 relationTable 也要改 (子表关联主表)
for (const t of parsedTables) {
const rt = String(t.relationTable || '')
if (rt && tableRenameMap[rt]) t.relationTable = tableRenameMap[rt]
}
raw.tables = JSON.stringify(parsedTables)
}
// 同步改 formData[].tableName (字段引用的旧表名)
if (raw.formData && Object.keys(tableRenameMap).length) {
try {
let fdRaw = raw.formData
for (const [oldT, newT] of Object.entries(tableRenameMap)) {
// 简单字符串替换 (tableName 是 JSON string 字段, 不会跟其他东西混)
fdRaw = fdRaw.split(`"tableName":"${oldT}"`).join(`"tableName":"${newT}"`)
}
raw.formData = fdRaw
} catch (e) {
log.warn(`formData tableName 替换失败: ${(e as Error).message}`)
}
}
// ---- v0.7: autoTable — 在目标 dbLinkId 重建物理表 ----
// 数据源优先级: _physicalSchema (export v0.7+ 拉的 DB schema) > tables[].fields[] (老 form 内嵌)
const wantsAutoTable = opts.autoTable !== false
type TableSchema = { table: string; tableName?: string; typeId?: string; fields: Record<string, unknown>[] }
const collectedTables: TableSchema[] = []
if (wantsAutoTable) {
if (raw._physicalSchema && raw._physicalSchema.length) {
// 主路径: v0.7 export 拉的
for (const p of raw._physicalSchema) collectedTables.push({ ...p })
} else if (parsedTables.length) {
// 兼容: 老 form 的 tables[].fields[] 内嵌字段
for (const t of parsedTables) {
const fields = Array.isArray(t.fields) ? (t.fields as Record<string, unknown>[]) : []
if (fields.length) {
collectedTables.push({
// 关键: 找原表名 — tableRenameMap 已把 t.table 改成 newName, 反查 oldName
table: Object.keys(tableRenameMap).find((k) => tableRenameMap[k] === t.table) || String(t.table || ''),
tableName: t.tableName as string | undefined,
typeId: t.typeId as string | undefined,
fields,
})
}
}
}
}
if (wantsAutoTable && collectedTables.length) {
log.info(`autoTable: 在 dbLinkId=${targetDbLinkId} 重建 ${collectedTables.length} 张物理表`)
for (const entry of collectedTables) {
const oldName = entry.table
const newName = tableRenameMap[oldName] || oldName
// 字段补齐 + 重排序 (DataModel API 要求 tableFieldList 含 index 字符串)
const fields = (entry.fields || []).map((f, i) => ({
field: f.field,
fieldName: f.fieldName || f.field,
dataType: f.dataType || 'varchar',
dataLength: f.dataLength != null ? String(f.dataLength) : '255',
primaryKey: f.primaryKey ?? 0,
allowNull: f.allowNull ?? 1,
autoIncrement: f.autoIncrement ?? 0,
identity: f.identity ?? 0,
index: String(i),
}))
// web/Java 真路径: { tableInfo: { table, tableName, newTable }, tableFieldList }
const body = {
tableInfo: {
table: newName,
tableName: entry.tableName || newName,
newTable: newName,
},
tableFieldList: fields,
}
try {
const dmR = await c.postJson<unknown>(`/system/DataModel/${targetDbLinkId}/Table`, body)
if (dmR.code === 200) {
log.ok(` ↳ 建表 ${newName} (字段 ×${fields.length})`)
} else {
const isExist = (dmR.msg || '').match(/exist|已存在/i)
if (isExist) log.warn(` ↳ ${newName} 已存在 (跳过)`)
else log.warn(` ↳ 建 ${newName} 失败 code=${dmR.code}: ${dmR.msg} (继续)`)
}
} catch (e) {
log.warn(` ↳ 建 ${newName} 异常: ${(e as Error).message} (继续)`)
}
}
} else if (wantsAutoTable && !collectedTables.length) {
log.warn('autoTable=true 但既无 _physicalSchema 也无 tables[].fields[], 跳过建表')
log.warn(' → 重新 dacli form export <id> 拿带 _physicalSchema 的 v0.7+ 格式')
}
// 清掉 _physicalSchema (后端不需要)
delete raw._physicalSchema
delete raw._exportedAt
// ---- POST /visualdev/Base ----
const r = await c.postJson(`/visualdev/Base`, raw)
if (r.code !== 200) {
log.error(`导入失败 code=${r.code}: ${r.msg}`)
process.exit(1)
}
// 反查 id (走 /visualdev/Base 全 form, 不走 /list 工作流子集)
const listR = await c.get<{ list: { id: string; enCode: string }[] }>('/visualdev/Base', {
keyword: newEnCode,
})
const newId = listR.data?.list.find((f) => f.enCode === newEnCode)?.id || '(unknown)'
log.ok(`导入成功 id=${newId} enCode=${newEnCode} dbLinkId=${targetDbLinkId}`)
if (Object.keys(tableRenameMap).length) {
log.info(` ↳ 表名映射: ${JSON.stringify(tableRenameMap)}`)
}
if (opts.release && raw.type !== 4 && newId !== '(unknown)') {
const rr = await c.postJson(`/visualdev/Base/${newId}/Actions/Release`, {})
if (rr.code === 200) log.ok('发布成功')
else log.warn(`发布失败 code=${rr.code}: ${rr.msg}`)
}
})
installAiHelpHook(cmd, {
purpose: '从 JSON 导入表单. v0.7 默认 --autoTable 在目标库重建物理表, 解 #15.',
required: { '<file>': 'JSON 文件路径' },
optional: {
'--enCode': '新 enCode (默认原 +_clone)',
'--fullName': '新中文名',
'--dbLinkId': '跨应用迁移强烈推荐传',
'--table': '新主表名 (默认 enCode 小写)',
'--release': '导入后立刻发布',
'--autoTable': '在目标库重建物理表 (默认 true)',
'--no-autoTable': '跳过重建 (老 export 无 _physicalSchema 时)',
},
example: 'dacli form import /tmp/leave.json --enCode=leave_clone --dbLinkId=206... --release',
source: {
api: 'POST /api/visualdev/Base + POST /api/system/DataModel/{dbLinkId}/Table',
web: 'web Form.vue:444 handleRequest + dataModel/index.vue createDataModel',
},
notes: [
'v0.7 默认重建物理表, 配合 form export 带的 _physicalSchema',
'旧 export 无 _physicalSchema 时, 加 --no-autoTable 跳过',
'tables[].table + formData[].tableName 都会重写, 避免目标库重名',
],
})
return cmd
}
+27
View File
@@ -0,0 +1,27 @@
/**
* commands/form/index.ts — `dacli form` 父命令 + 子命令注册
*/
import { Command } from 'commander'
import { buildFormListCommand } from './list.ts'
import { buildFormInfoCommand } from './info.ts'
import { buildFormCreateCommand } from './create.ts'
import { buildFormReleaseCommand } from './release.ts'
import { buildFormDeleteCommand } from './delete.ts'
import { buildFormExportCommand } from './export.ts'
import { buildFormImportCommand } from './import.ts'
import { buildFormCloneCommand } from './clone.ts'
import { buildFormValidateCommand } from './validate.ts'
export function buildFormCommand(): Command {
const cmd = new Command('form').description('表单 CRUD (list/info/create/release/delete/export/import/clone/validate)')
cmd.addCommand(buildFormListCommand())
cmd.addCommand(buildFormInfoCommand())
cmd.addCommand(buildFormCreateCommand())
cmd.addCommand(buildFormReleaseCommand())
cmd.addCommand(buildFormDeleteCommand())
cmd.addCommand(buildFormExportCommand())
cmd.addCommand(buildFormImportCommand())
cmd.addCommand(buildFormCloneCommand())
cmd.addCommand(buildFormValidateCommand())
return cmd
}
+41
View File
@@ -0,0 +1,41 @@
/**
* commands/form/info.ts — 拉表单完整 schema
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { printJson, log } from '../../core/log.ts'
import type { FormDetail } from '../../core/types.ts'
export function buildFormInfoCommand(): Command {
const cmd = new Command('info')
.description('拉表单完整 schema (含 formData/columnData/tables)')
.argument('<id>', '表单 id')
.option('--summary', '只打概要 (id/enCode/state/type/webType/dbLinkId/字段数)', false)
.action(async (id: string, opts: { summary?: boolean }) => {
const c = await JnpfClient.fromToken()
const r = await c.get<FormDetail>(`/visualdev/Base/${id}`)
const data = c.ok(r)
if (opts.summary) {
const tables = (Array.isArray(data.tables) ? data.tables : []) as Array<{ table?: string }>
log.ok(`${data.fullName} (${data.enCode})`)
log.dim(`id : ${data.id}`)
log.dim(`state : ${data.state} type: ${data.type} webType: ${data.webType}`)
log.dim(`dbLinkId : ${data.dbLinkId || '(none)'}`)
log.dim(`category : ${data.category || '(none)'}`)
log.dim(`tables : ${tables.length} (${tables.map((t) => t.table).join(', ')})`)
return
}
printJson(data)
})
installAiHelpHook(cmd, {
purpose: '拉表单完整 schema. clone 前先 info 看结构',
required: { '<id>': '表单 id' },
optional: { '--summary': '只打概要' },
example: ['dacli form info 123456 --summary', 'dacli form info 123456 > /tmp/x.json'],
source: { api: 'GET /api/visualdev/Base/:id' },
})
return cmd
}
+68
View File
@@ -0,0 +1,68 @@
/**
* commands/form/list.ts — 列出当前应用的所有表单 (state/enCode/fullName)
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import type { FormSummary } from '../../core/types.ts'
interface ListResp {
list: FormSummary[]
pagination?: { total: number; currentPage: number; pageSize: number }
}
export function buildFormListCommand(): Command {
const cmd = new Command('list')
.description('列出当前应用所有表单 (state=0 草稿, state=1 已发布)')
.option('--keyword <k>', '关键字 (匹配 fullName/enCode)')
.option('--state <s>', '过滤 state (0|1)', (v) => parseInt(v, 10))
.option('--limit <n>', '最多取 N 条 (默认 100)', (v) => parseInt(v, 10), 100)
.option('--json', '原始 JSON', false)
.action(async (opts: { keyword?: string; state?: number; limit: number; json?: boolean }) => {
const c = await JnpfClient.fromToken()
// GET /api/visualdev/Base — 公开方法 (返当前 systemId 下全部 form,
// 含 enableFlow=0/1/null).
// 注: GET /api/visualdev/Base/list 是工作流子集 (后端强制 setEnableFlow(1)),
// 会漏非工作流 form — 历史误用导致 v0.5 报"72/72"实际只覆盖 enableFlow=1 部分.
// 修复见 jnpf VisualdevController#list (line 133) vs #getList (line 179).
const r = await c.get<ListResp>('/visualdev/Base', {
keyword: opts.keyword,
currentPage: 1,
pageSize: opts.limit,
})
const data = c.ok(r)
let list = data.list || []
if (opts.state !== undefined) list = list.filter((f) => f.state === opts.state)
// state filter 在 list 接口上不可靠 (字段缺), 用 form info 兜底? 这里仅过 list 自带字段
if (opts.json) {
printJson({ total: list.length, list })
return
}
log.ok(`共 ${list.length} 张 (app=${c.appCode})`)
console.log('ID'.padEnd(20), 'TYPE', 'FLOW', 'enCode'.padEnd(32), 'fullName')
for (const f of list) {
console.log(
String(f.id).padEnd(20),
String(f.type ?? '-').padEnd(4),
String((f as unknown as { enableFlow?: number }).enableFlow ?? '-').padEnd(4),
(f.enCode || '').padEnd(32),
f.fullName,
)
}
})
installAiHelpHook(cmd, {
purpose: '列出当前应用的所有表单. AI 干活前先跑一下看有什么已有表单, 优先 clone',
optional: {
'--keyword': '过滤 (服务器侧)',
'--state': '过滤 state (0=草稿 1=已发布)',
'--limit': '最多 N 条',
'--json': '原始 JSON',
},
example: ['dacli form list', 'dacli form list --json | jq \'.list[] | select(.enCode=="leaveApply") | .id\''],
source: { api: 'GET /api/visualdev/Base (全 form, 含 enableFlow=0/1/null)' },
})
return cmd
}
+38
View File
@@ -0,0 +1,38 @@
/**
* commands/form/release.ts — 发布表单 (state 0 → 1)
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
export function buildFormReleaseCommand(): Command {
const cmd = new Command('release')
.description('发布表单 (state 0→1). type=4 视图会 400 (软跳过 --soft)')
.argument('<id>', '表单 id')
.option('--soft', '发布失败不退出 (用于 type=4)', false)
.action(async (id: string, opts: { soft?: boolean }) => {
const c = await JnpfClient.fromToken()
const r = await c.postJson<unknown>(`/visualdev/Base/${id}/Actions/Release`, {})
if (r.code === 200) {
log.ok(`发布成功 id=${id} (state=1)`)
return
}
if (opts.soft) {
log.warn(`发布失败 (软跳过) code=${r.code}: ${r.msg}`)
return
}
log.error(`发布失败 code=${r.code}: ${r.msg}`)
process.exit(1)
})
installAiHelpHook(cmd, {
purpose: '把表单从 state=0 切到 state=1, 前端列表才能看到',
required: { '<id>': '表单 id' },
optional: { '--soft': 'type=4 时软跳过' },
example: 'dacli form release 1234567890',
source: { api: 'POST /api/visualdev/Base/:id/Actions/Release' },
})
return cmd
}
+94
View File
@@ -0,0 +1,94 @@
/**
* commands/form/validate.ts — 校验表单结构 (columnData __config__ 完整性)
*
* 镜像 Java 版 `dacli form validate <id>` 能力
* 主要检查:
* - formData.fields 每项有 __config__
* - columnData.fields 每项有 __config__ (新版 JNPF 缺会白屏)
* - tables 有 dbLinkId
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import type { FormDetail } from '../../core/types.ts'
interface ValidationIssue {
level: 'ERROR' | 'WARN'
path: string
message: string
}
function safeParse(s: unknown): unknown {
if (typeof s !== 'string') return s
try {
return JSON.parse(s)
} catch {
return null
}
}
function validate(form: FormDetail): ValidationIssue[] {
const issues: ValidationIssue[] = []
const formData = safeParse(form.formData) as { fields?: unknown[] } | null
const columnData = safeParse(form.columnData) as { fields?: unknown[] } | null
if (!formData) issues.push({ level: 'ERROR', path: 'formData', message: 'formData 解析失败或为空' })
else if (!Array.isArray(formData.fields)) issues.push({ level: 'WARN', path: 'formData.fields', message: 'fields 不是数组' })
if (columnData?.fields) {
columnData.fields.forEach((f, i) => {
const ff = f as { __config__?: unknown; __vModel__?: string }
if (!ff.__config__) {
issues.push({
level: 'ERROR',
path: `columnData.fields[${i}] (${ff.__vModel__ || '?'})`,
message: '缺 __config__ → 浏览器列表会白屏',
})
}
})
}
if (Array.isArray(form.tables) && form.tables.length > 0 && form.type !== 4 && !form.dbLinkId) {
issues.push({ level: 'ERROR', path: 'dbLinkId', message: 'type≠4 必须有 dbLinkId' })
}
return issues
}
export function buildFormValidateCommand(): Command {
const cmd = new Command('validate')
.description('校验表单结构 (columnData __config__ 完整性等)')
.argument('<id>', '表单 id')
.option('--json', '原始 JSON', false)
.action(async (id: string, opts: { json?: boolean }) => {
const c = await JnpfClient.fromToken()
const r = await c.get<FormDetail>(`/visualdev/Base/${id}`)
const form = c.ok(r)
const issues = validate(form)
if (opts.json) {
printJson({ id, enCode: form.enCode, issues, pass: issues.filter((i) => i.level === 'ERROR').length === 0 })
return
}
if (issues.length === 0) {
log.ok(`PASS ${form.enCode} (${id})`)
return
}
log.warn(`${form.enCode} 发现 ${issues.length} 个问题`)
for (const i of issues) {
const fn = i.level === 'ERROR' ? log.error : log.warn
fn(`[${i.level}] ${i.path}: ${i.message}`)
}
const failed = issues.filter((i) => i.level === 'ERROR').length > 0
if (failed) process.exit(2)
})
installAiHelpHook(cmd, {
purpose: '校验表单结构. columnData 缺 __config__ 会浏览器白屏',
required: { '<id>': '表单 id' },
example: 'dacli form validate 12345',
notes: ['ERROR → 退出码 2', 'Java 版有 --fix 自动修复, TS 版 W2+ 实现'],
})
return cmd
}
+50
View File
@@ -0,0 +1,50 @@
/**
* commands/login.ts
*/
import { Command } from 'commander'
import { JnpfClient } from '../core/client.ts'
import { DEFAULT_ACCOUNT, DEFAULT_APP_CODE, DEFAULT_PASSWORD, getTokenPath } from '../core/config.ts'
import { installAiHelpHook } from '../core/help.ts'
import { log } from '../core/log.ts'
export function buildLoginCommand(): Command {
const cmd = new Command('login')
.description('登录 JNPF (默认 admin/123456@developSystem), 持久化 token 到 .dacli-token/token.json')
.option('--account <a>', '账号', DEFAULT_ACCOUNT)
.option('--password <p>', '密码 (明文; 96 字符 hex 视为已加密)', DEFAULT_PASSWORD)
.option('--appCode <c>', '应用代码 (developSystem | workSystem | tds)', DEFAULT_APP_CODE)
.option('--baseUrl <u>', 'JNPF API 根地址 (含 /api)')
.action(async (opts: { account: string; password: string; appCode: string; baseUrl?: string }) => {
const c = await JnpfClient.login({
account: opts.account,
password: opts.password,
appCode: opts.appCode,
baseUrl: opts.baseUrl,
forceLogin: true,
})
log.ok(`登录成功: ${c.account} @ ${c.appCode}`)
log.dim(`baseUrl : ${c.baseUrl}`)
log.dim(`token : ${c.token.slice(0, 32)}... (${c.token.length} chars)`)
if (c.dbLinkId) log.dim(`dbLinkId : ${c.dbLinkId}`)
log.dim(`saved to : ${getTokenPath()}`)
})
installAiHelpHook(cmd, {
purpose: '登录 JNPF, 把 token 写到 .dacli-token/token.json, 后续命令自动复用',
optional: {
'--account': '账号 (默认 admin)',
'--password': '密码 (默认 123456; 已是 96 字符 hex 时跳过加密)',
'--appCode': '应用代码 (默认 developSystem)',
'--baseUrl': '强制指定 baseUrl, 否则按 [env JNPF_BASE_URL → http://nginx/api → http://127.0.0.1:30000/api] 依次尝试',
},
example: 'dacli login --appCode=tds',
source: { web: 'web/.../auth.ts:27 loginApi', api: 'POST /api/oauth/Login' },
notes: [
'token 7 天有效',
'已加密的 96 字符 hex 不会重复加密',
'detectDbLinkId 自动从 /system/DataSource 拉业务库 id',
],
})
return cmd
}
+172
View File
@@ -0,0 +1,172 @@
/**
* commands/menu/create.ts — 创建菜单
*
* v0.6 重写: 优先用 web 真路径 (POST /api/visualdev/Base/{formId}/Actions/Module).
* - 体现 prompt §2.1 "复用 web 源码" 初心
* - 后端自动构造 moduleId/propertyJson/urlAddress/pageAddress 等所有字段
* - 移植自 web/views/onlineDev/formDesign/components/CreateMenuModal.vue handleSubmit (line ~120)
*
* 两种模式:
* A) 挂表单菜单 (--formId 给) — 走 web Actions/Module 高级 API
* B) 普通菜单 (目录/外链) — 走 POST /api/system/Menu 低级 API
*
* Actions/Module body (来自 CreateMenuModal.vue:99-119):
* {
* pc: 1, // 桌面端发布
* app: 0, // 移动端不发布 (默认)
* pcModuleParentId: ["0"], // 顶级 (数组, 可挂多个父)
* appModuleParentId: [],
* platformRelease: '{"pc":1,"app":0}'
* }
*
* 关键: 顶级父 menuId 用 "0" (web 端通过 getMenuSelectorFilter 拿默认根).
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts {
fullName: string
enCode?: string
formId?: string
parentId?: string
pcParents?: string
appParents?: string
pc?: boolean
app?: boolean
type?: string
urlAddress?: string
icon?: string
json?: boolean
}
export function buildMenuCreateCommand(): Command {
const cmd = new Command('create')
.description('创建菜单. --formId 给则走 web 真路径 Actions/Module, 否则走低级 POST /system/Menu')
.requiredOption('--fullName <n>', '菜单中文名')
.option('--enCode <e>', '菜单英文编码 (默认=fullName)')
.option('--formId <f>', '关联 form id (挂表单菜单时给 → 走 Actions/Module)')
.option('--pcParents <ids>', '挂表单时桌面端父菜单 id 列表 (逗号分隔, 默认 "0" 顶级)')
.option('--appParents <ids>', '挂表单时移动端父菜单 id 列表 (逗号分隔, 默认空 = 不发布)')
.option('--no-pc', '挂表单时不发布桌面端 (默认 true)')
.option('--app', '挂表单时发布移动端 (默认 false)', false)
.option('--parentId <p>', '低级模式: 父菜单 id', '-1')
.option('--type <t>', '低级模式 type: 1=目录 2=Vue扩展 3=VisualDev 7=外链', '1')
.option('--urlAddress <u>', '低级模式: URL')
.option('--icon <i>', '低级模式: 图标')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
// 模式 A: 挂表单菜单 — 走 web 真路径
if (opts.formId) {
const pcParents = (opts.pcParents ?? '0').split(',').filter(Boolean)
const appParents = opts.appParents ? opts.appParents.split(',').filter(Boolean) : []
const pc = opts.pc === false ? 0 : 1
const app = opts.app ? 1 : 0
if (!pc && !app) {
log.error('至少一个发布平台 (pc / app), 当前都是 0')
process.exit(2)
}
const body = {
pc,
app,
pcModuleParentId: pcParents,
appModuleParentId: appParents,
platformRelease: JSON.stringify({ pc, app }),
}
log.info(`POST /visualdev/Base/${opts.formId}/Actions/Module (web 真路径)`)
const r = await c.postJson(`/visualdev/Base/${opts.formId}/Actions/Module`, body)
if (r.code !== 200) {
log.error(`menu create (Actions/Module) 失败 code=${r.code}: ${r.msg}`)
if (opts.json) printJson(r)
process.exit(1)
}
log.ok(`✓ 菜单发布成功 (formId=${opts.formId}, pc=${pc}, app=${app})`)
log.ok(' ↳ 后端已自动构造 moduleId/propertyJson/urlAddress/pageAddress + 给当前角色授权')
if (opts.json) printJson(r)
return
}
// 模式 B: 低级 POST /system/Menu (目录/外链等)
const enCode = opts.enCode || opts.fullName
const type = parseInt(opts.type || '1', 10)
const icon = opts.icon ?? (type === 1 ? 'icon-ym icon-ym-folder' : '')
const body: Record<string, unknown> = {
fullName: opts.fullName,
enCode,
parentId: opts.parentId || '-1',
type,
enabledMark: 1,
sortCode: 0,
category: 'Web',
linkTarget: '_self',
isButtonAuthorize: 1,
isColumnAuthorize: 1,
isDataAuthorize: 1,
isFormAuthorize: 1,
icon,
propertyJson: '{"moduleId":"","iconBackgroundColor":"","isTree":0}',
}
if (type === 7 && !opts.urlAddress) {
log.error('type=7 (外链) 必须传 --urlAddress')
process.exit(2)
}
if (opts.urlAddress) {
body.urlAddress = opts.urlAddress
body.pageAddress = opts.urlAddress
}
log.info(`POST /system/Menu ${enCode} (type=${type})`)
const r = await c.postJson<{ id?: string }>('/system/Menu', body)
if (r.code !== 200) {
log.error(`menu create 失败 code=${r.code}: ${r.msg}`)
process.exit(1)
}
let menuId: string | undefined = r.data?.id
if (!menuId) {
const listR = await c.get<{ list?: { id: string; enCode: string }[] }>('/system/Menu', {
currentPage: 1,
pageSize: 50,
parentId: body.parentId as string,
keyword: enCode,
})
menuId = listR.data?.list?.find((m) => m.enCode === enCode)?.id
}
log.ok(`✓ 创建: id=${menuId || '(unknown)'} enCode=${enCode}`)
if (opts.json) printJson({ id: menuId, enCode, ...body })
})
installAiHelpHook(cmd, {
purpose: '创建菜单. 挂表单菜单 (--formId) 走 web 真路径 Actions/Module, 后端自动处理所有字段',
required: { '--fullName': '中文名' },
optional: {
'--formId': '关联 form id (走 web Actions/Module 高级 API)',
'--pcParents': '桌面端父菜单 ids (逗号分隔, 默认 "0" 顶级)',
'--no-pc': '不发布桌面端',
'--app': '同时发布移动端',
'--enCode': '英文编码 (低级模式用)',
'--type': '低级模式 type',
'--parentId': '低级模式父 id',
'--urlAddress': '低级模式 URL',
},
example: [
'# 挂表单菜单 (推荐 web 真路径)',
'dacli menu create --fullName="员工培训" --formId=835141398800901061',
'# 挂在指定父菜单',
'dacli menu create --fullName="员工培训" --formId=xxx --pcParents=父menuId1,父menuId2',
'# 顶级目录',
'dacli menu create --fullName="人事管理" --enCode=hr --type=1',
],
source: {
api: 'POST /api/visualdev/Base/{formId}/Actions/Module (挂表单) / POST /api/system/Menu (普通)',
ref: 'web/views/onlineDev/formDesign/components/CreateMenuModal.vue',
},
notes: [
'挂表单菜单优先 --formId, 后端自动给当前用户角色授权 + 构造 moduleId/propertyJson',
'web 端 getReleaseMenu 可查是否已发布',
'前端 storage 缓存可能 1-2s 延迟才看到新菜单, 重登/F5 兜底',
],
})
return cmd
}
+33
View File
@@ -0,0 +1,33 @@
/**
* commands/menu/delete.ts — 删除菜单
*
* API: DELETE /api/system/Menu/{id}
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
interface Opts { id: string; yes?: boolean }
export function buildMenuDeleteCommand(): Command {
const cmd = new Command('delete')
.description('删除菜单 (按 id)')
.requiredOption('--id <id>', '菜单 id')
.option('--yes', '跳过确认', false)
.action(async (opts: Opts) => {
if (!opts.yes) { log.warn('传 --yes 确认删除'); process.exit(2) }
const c = await JnpfClient.fromToken()
const r = await c.del(`/system/Menu/${opts.id}`)
if (r.code !== 200) { log.error(`menu delete 失败: ${r.msg}`); process.exit(1) }
log.ok(`已删除: ${opts.id}`)
})
installAiHelpHook(cmd, {
purpose: '删除菜单.',
required: { '--id': '菜单 id', '--yes': '确认' },
example: 'dacli menu delete --id=123 --yes',
source: { api: 'DELETE /api/system/Menu/{id}' },
})
return cmd
}
+17
View File
@@ -0,0 +1,17 @@
/**
* commands/menu/index.ts — menu 父命令
*/
import { Command } from 'commander'
import { buildMenuListCommand } from './list.ts'
import { buildMenuCreateCommand } from './create.ts'
import { buildMenuDeleteCommand } from './delete.ts'
import { buildMenuUnreleaseCommand } from './unrelease.ts'
export function buildMenuCommand(): Command {
const cmd = new Command('menu').description('菜单管理 (按 app)')
cmd.addCommand(buildMenuListCommand())
cmd.addCommand(buildMenuCreateCommand())
cmd.addCommand(buildMenuDeleteCommand())
cmd.addCommand(buildMenuUnreleaseCommand())
return cmd
}
+46
View File
@@ -0,0 +1,46 @@
/**
* commands/menu/list.ts — 菜单列表 (按 system)
*
* API: GET /api/system/Menu/ModuleBySystem 或 /api/system/Menu?keyword=
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts { json?: boolean; keyword?: string; flat?: boolean }
export function buildMenuListCommand(): Command {
const cmd = new Command('list')
.description('菜单列表 (按当前 app system 过滤)')
.option('--keyword <k>', '按名称搜索')
.option('--flat', '不按树形打印, 直接平铺', false)
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
// /ModuleBySystem 自动按请求头 App-Code 过滤
const r = await c.get<unknown>('/system/Menu/ModuleBySystem', { keyword: opts.keyword })
if (r.code !== 200) { log.error(`menu list 失败: ${r.msg}`); process.exit(1) }
if (opts.json) { printJson(r.data); return }
const list = (Array.isArray(r.data) ? r.data : (r.data as { list?: unknown[] })?.list) || []
log.info(`当前 app 共 ${list.length} 个菜单项`)
console.log('ID FULL_NAME ENCODE URL')
console.log('-'.repeat(100))
for (const m of list as Record<string, unknown>[]) {
const id = String(m.id || '').padEnd(36)
const name = String(m.fullName || '').padEnd(22)
const enc = String(m.enCode || '').padEnd(20)
console.log(`${id}${name}${enc}${m.urlAddress || ''}`)
}
})
installAiHelpHook(cmd, {
purpose: '列出当前 app 的菜单树 (按请求头 App-Code 过滤).',
required: {},
optional: { '--keyword': '搜索关键字', '--flat': '平铺打印' },
example: 'dacli menu list',
source: { api: 'GET /api/system/Menu/ModuleBySystem' },
notes: ['先 dacli switch-app --appCode=X 切到目标应用, 才能看到对应菜单'],
})
return cmd
}
+51
View File
@@ -0,0 +1,51 @@
/**
* commands/menu/unrelease.ts — 取消表单菜单发布 (web 真路径)
*
* web 真行为 (CreateMenuModal.vue handleSubmit, pc=0 + app=0 仍可发):
* POST /api/visualdev/Base/{formId}/Actions/Module
* body: {pc:0, app:0, pcModuleParentId:[], appModuleParentId:[], platformRelease:'{"pc":0,"app":0}'}
* 返 200 "Synchronization successful" — 删除已挂菜单 (前端 UI 有"至少一个平台"校验, 后端无)
*
* 用途: DELETE /api/system/Menu/{id} 报 "System abnormality" 时的兜底.
* 只对 type=3 (VisualDev) + 已 pcIsRelease=1 的菜单有效, 普通目录/外链请直接用 menu delete.
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
interface Opts { formId: string }
export function buildMenuUnreleaseCommand(): Command {
const cmd = new Command('unrelease')
.description('取消表单菜单发布 (form-driven, 走 web Actions/Module 真路径)')
.requiredOption('--formId <f>', '表单 id')
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const body = {
pc: 0,
app: 0,
pcModuleParentId: [] as string[],
appModuleParentId: [] as string[],
platformRelease: JSON.stringify({ pc: 0, app: 0 }),
}
log.info(`POST /visualdev/Base/${opts.formId}/Actions/Module pc=0 app=0`)
const r = await c.postJson(`/visualdev/Base/${opts.formId}/Actions/Module`, body)
if (r.code !== 200) {
log.error(`unrelease 失败 code=${r.code}: ${r.msg}`)
process.exit(1)
}
log.ok(`✓ 已取消挂菜单 (formId=${opts.formId})`)
})
installAiHelpHook(cmd, {
purpose: '取消 form 的菜单发布. 用于 dacli menu delete 失败时兜底 (DELETE /api/system/Menu/X 报 System abnormality).',
required: { '--formId': '表单 id' },
example: 'dacli menu unrelease --formId=835141398800901061',
source: {
api: 'POST /api/visualdev/Base/{formId}/Actions/Module',
ref: 'web/views/onlineDev/formDesign/components/CreateMenuModal.vue (前端有 pc/app 至少一个校验, 后端无)',
},
notes: ['仅适用于 type=3 VisualDev 菜单', '普通目录/外链请用 menu delete'],
})
return cmd
}
+49
View File
@@ -0,0 +1,49 @@
/**
* commands/status.ts
*/
import { Command } from 'commander'
import { loadToken, getTokenPath, currentBaseUrl } from '../core/config.ts'
import { installAiHelpHook } from '../core/help.ts'
import { log } from '../core/log.ts'
export function buildStatusCommand(): Command {
const cmd = new Command('status')
.description('显示当前登录状态 + baseUrl + appCode + dbLinkId + token 路径')
.option('--json', '以 JSON 输出 (便于脚本)', false)
.action((opts: { json?: boolean }) => {
const t = loadToken()
if (opts.json) {
console.log(JSON.stringify({
tokenPath: getTokenPath(),
baseUrl: t?.baseUrl || currentBaseUrl(),
loggedIn: !!t,
account: t?.account,
appCode: t?.appCode,
dbLinkId: t?.dbLinkId,
loginAt: t?.loginAt,
tokenLen: t?.token.length,
}, null, 2))
return
}
if (!t) {
log.warn('未登录. 先跑: dacli login')
log.dim(`baseUrl: ${currentBaseUrl()}`)
log.dim(`token path: ${getTokenPath()}`)
return
}
log.ok(`已登录: ${t.account} @ ${t.appCode}`)
log.dim(`baseUrl : ${t.baseUrl}`)
log.dim(`dbLinkId : ${t.dbLinkId || '(unknown)'}`)
log.dim(`loginAt : ${t.loginAt}`)
log.dim(`token len : ${t.token.length}`)
log.dim(`token path: ${getTokenPath()}`)
})
installAiHelpHook(cmd, {
purpose: '显示当前登录状态. 写脚本前先跑一下确认登录态',
optional: { '--json': '以 JSON 输出' },
example: 'dacli status',
})
return cmd
}
+36
View File
@@ -0,0 +1,36 @@
/**
* commands/switch-app.ts — 切换 appCode (登录新 app 并覆盖 token)
*/
import { Command } from 'commander'
import { JnpfClient } from '../core/client.ts'
import { DEFAULT_ACCOUNT, DEFAULT_PASSWORD, loadToken } from '../core/config.ts'
import { installAiHelpHook } from '../core/help.ts'
import { log } from '../core/log.ts'
export function buildSwitchAppCommand(): Command {
const cmd = new Command('switch-app')
.description('切换当前应用 (重新登录新 appCode 并覆盖 token)')
.requiredOption('--appCode <c>', '目标应用代码')
.option('--account <a>', '账号')
.option('--password <p>', '密码')
.action(async (opts: { appCode: string; account?: string; password?: string }) => {
const cached = loadToken()
const c = await JnpfClient.login({
account: opts.account || cached?.account || DEFAULT_ACCOUNT,
password: opts.password || DEFAULT_PASSWORD,
appCode: opts.appCode,
baseUrl: cached?.baseUrl,
forceLogin: true,
})
log.ok(`切换成功: ${c.account} @ ${c.appCode}`)
log.dim(`dbLinkId : ${c.dbLinkId || '(unknown)'}`)
})
installAiHelpHook(cmd, {
purpose: '切换当前应用, 重新登录并覆盖本地 token. baseline 复刻常用',
required: { '--appCode': '目标应用 (developSystem | workSystem | tds)' },
example: ['dacli switch-app --appCode=developSystem', 'dacli switch-app --appCode=tds'],
})
return cmd
}
+50
View File
@@ -0,0 +1,50 @@
/**
* commands/workflow/approve.ts — 审批流程
*
* API: POST /api/workflow/operator/Audit/{operatorId}
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts {
operatorId: string
status: string
opinion?: string
json?: boolean
}
export function buildWorkflowApproveCommand(): Command {
const cmd = new Command('approve')
.description('审批一个流程任务 (operatorId 来自 --todo=1 列表)')
.requiredOption('--operatorId <id>', '审批节点 id (operatorId)')
.requiredOption('--status <0|1|2>', '0=同意 1=不同意 2=退回', '0')
.option('--opinion <text>', '审批意见')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const body = {
status: Number(opts.status),
opinion: opts.opinion || '',
}
log.info(`POST /workflow/operator/Audit/${opts.operatorId} status=${opts.status}`)
const r = await c.postJson<unknown>(`/workflow/operator/Audit/${opts.operatorId}`, body)
if (r.code !== 200) {
log.error(`approve 失败: ${r.msg}`)
if (opts.json) printJson(r)
process.exit(1)
}
log.ok('审批成功')
if (opts.json) printJson(r.data)
})
installAiHelpHook(cmd, {
purpose: '审批流程节点. 0=同意 1=不同意 2=退回.',
required: { '--operatorId': '审批节点 id', '--status': '0/1/2' },
optional: { '--opinion': '审批意见' },
example: 'dacli workflow approve --operatorId=123 --status=0 --opinion=同意',
source: { api: 'POST /api/workflow/operator/Audit/{operatorId}' },
})
return cmd
}
+15
View File
@@ -0,0 +1,15 @@
/**
* commands/workflow/index.ts — workflow 父命令
*/
import { Command } from 'commander'
import { buildWorkflowListCommand } from './list.ts'
import { buildWorkflowLaunchCommand } from './launch.ts'
import { buildWorkflowApproveCommand } from './approve.ts'
export function buildWorkflowCommand(): Command {
const cmd = new Command('workflow').description('流程引擎 (模板/发起/审批)')
cmd.addCommand(buildWorkflowListCommand())
cmd.addCommand(buildWorkflowLaunchCommand())
cmd.addCommand(buildWorkflowApproveCommand())
return cmd
}
+57
View File
@@ -0,0 +1,57 @@
/**
* commands/workflow/launch.ts — 发起流程
*
* API: POST /api/workflow/task
*
* Body: { flowId, formId, data, ... }
*
* 注意: 需绑工作流的 form (form.enableFlow=1) 才能发起
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts {
flowId: string
formId: string
data: string
json?: boolean
}
export function buildWorkflowLaunchCommand(): Command {
const cmd = new Command('launch')
.description('发起流程 (绑定 formId + flowId, data 为表单数据 JSON)')
.requiredOption('--flowId <id>', '流程模板 id')
.requiredOption('--formId <id>', '绑定的表单 id')
.requiredOption('--data <json>', '表单数据 JSON 字符串 (formData 字段值)')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const body = {
flowId: opts.flowId,
formId: opts.formId,
data: opts.data,
status: 0,
approverUserId: '',
}
log.info(`POST /workflow/task flowId=${opts.flowId} formId=${opts.formId}`)
const r = await c.postJson<{ id?: string; taskId?: string }>('/workflow/task', body)
if (r.code !== 200) {
log.error(`launch 失败 (code=${r.code}): ${r.msg}`)
if (opts.json) printJson(r)
process.exit(1)
}
log.ok(`发起成功: taskId=${r.data?.id || r.data?.taskId || '(unknown)'}`)
if (opts.json) printJson(r.data)
})
installAiHelpHook(cmd, {
purpose: '发起一个流程实例. 需 form.enableFlow=1.',
required: { '--flowId': '流程模板 id', '--formId': '绑定 form id', '--data': '表单数据 JSON' },
example: `dacli workflow launch --flowId=<flowId> --formId=<formId> --data='{"f_name":"张三"}'`,
source: { api: 'POST /api/workflow/task' },
notes: ['发起前确认 form.enableFlow=1 + flowId 已绑'],
})
return cmd
}
+56
View File
@@ -0,0 +1,56 @@
/**
* commands/workflow/list.ts — 流程模板/任务 列表
*
* API:
* GET /api/workflow/template[?category=X] 模板
* GET /api/workflow/operator/List/{type} 我的待办 (type=1 待审批, 2 已审批, 3 抄送)
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface ListOpts {
category?: string
todo?: string
pageSize?: string
json?: boolean
}
export function buildWorkflowListCommand(): Command {
const cmd = new Command('list')
.description('流程模板 / 我的待办 列表')
.option('--category <c>', '模板分类')
.option('--todo <type>', '我的待办 (1=待审批 2=已审批 3=抄送), 启用此模式时 category 忽略', '0')
.option('--pageSize <s>', '每页', '50')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: ListOpts) => {
const c = await JnpfClient.fromToken()
const todo = Number(opts.todo || '0')
const path = todo > 0
? `/workflow/operator/List/${todo}`
: `/workflow/template${opts.category ? `?category=${opts.category}` : ''}`
const r = await c.get<{ list?: { id: string; fullName: string; enCode?: string; category?: string }[] }>(path, {
currentPage: 1,
pageSize: opts.pageSize,
})
if (r.code !== 200) { log.error(`workflow list 失败: ${r.msg}`); process.exit(1) }
const list = r.data?.list || []
if (opts.json) { printJson(r.data); return }
log.info(`${path} 共 ${list.length} 条`)
console.log('ID FULL_NAME ENCODE CATEGORY')
console.log('-'.repeat(100))
for (const t of list) {
console.log(`${String(t.id || '').padEnd(36)}${String(t.fullName || '').padEnd(22)}${String(t.enCode || '').padEnd(22)}${t.category || ''}`)
}
})
installAiHelpHook(cmd, {
purpose: '看流程模板 (--category) 或 我的待办 (--todo 1/2/3).',
required: {},
optional: { '--category': '模板分类', '--todo': '1=待审批 2=已审批 3=抄送', '--pageSize': '每页' },
example: ['dacli workflow list', 'dacli workflow list --todo=1'],
source: { api: 'GET /api/workflow/template 或 /api/workflow/operator/List/{type}' },
})
return cmd
}
+197
View File
@@ -0,0 +1,197 @@
/**
* client.ts — JnpfClient
*
* 借鉴 ddcc/jnpf.ts (已验证), 加 token 自动加载 + baseUrl 兜底。
*
* 关键: baseUrl 必须含 /api, path 不再带 /api 前缀。
* 例: baseUrl='http://nginx/api' + path='/visualdev/Base/list' → 'http://nginx/api/visualdev/Base/list'
*/
import { encryptPassword, isEncrypted } from './crypto.ts'
import { loadToken, saveToken, baseUrlCandidates } from './config.ts'
import { DacliError } from './types.ts'
import type { JnpfResp, LoginResp, TokenFile } from './types.ts'
import { log } from './log.ts'
export interface ClientOptions {
baseUrl?: string
appCode?: string
account?: string
password?: string
/** true=强制不读 token, 重新登录 */
forceLogin?: boolean
}
export class JnpfClient {
baseUrl: string
appCode: string
account: string
password: string
token = ''
/** 业务库 id, login 后自动拉 */
dbLinkId?: string
constructor(opt: ClientOptions = {}) {
this.baseUrl = (opt.baseUrl || '').replace(/\/+$/, '')
this.appCode = opt.appCode || ''
this.account = opt.account || ''
this.password = opt.password || ''
}
/** 走 token 缓存, 没就登录 */
static async fromToken(opt: ClientOptions = {}): Promise<JnpfClient> {
const cached = opt.forceLogin ? null : loadToken()
if (cached && !opt.forceLogin) {
const c = new JnpfClient({
baseUrl: opt.baseUrl || cached.baseUrl,
appCode: opt.appCode || cached.appCode,
account: opt.account || cached.account,
password: opt.password || '',
})
c.token = cached.token
c.dbLinkId = cached.dbLinkId
return c
}
// 没缓存或强制 → 完整 login
return JnpfClient.login(opt)
}
/** 完整登录 (encrypt + POST /oauth/Login + 持久化) */
static async login(opt: ClientOptions = {}): Promise<JnpfClient> {
const candidates = opt.baseUrl ? [opt.baseUrl] : baseUrlCandidates()
let lastErr: Error | null = null
for (const base of candidates) {
try {
const c = new JnpfClient({ ...opt, baseUrl: base })
await c.doLogin()
await c.detectDbLinkId()
c.persist()
return c
} catch (e) {
lastErr = e as Error
log.debug(`login via ${base} failed: ${(e as Error).message}`)
}
}
throw lastErr || new DacliError('所有 baseUrl 候选都失败, 请确认 JNPF 是否启动')
}
private async doLogin(): Promise<void> {
const encrypted = isEncrypted(this.password) ? this.password : encryptPassword(this.password)
const body = new URLSearchParams({
account: this.account,
password: encrypted,
code: '',
origin: 'hash',
timestamp: '0',
jnpf_ticket: '',
grant_type: 'password',
}).toString()
const url = `${this.baseUrl}/oauth/Login`
log.debug('POST', url)
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
})
const text = await res.text()
const r = parseJson<LoginResp>(text)
if (r.code !== 200 || !r.data) {
throw new DacliError(`登录失败 (code ${r.code}): ${r.msg}`, r.code, text.slice(0, 200))
}
this.token = r.data.token
}
/** 拉业务库 id (非主库). 失败不致命, 仅 debug */
private async detectDbLinkId(): Promise<void> {
try {
const r = await this.get<{ list?: Array<{ id: string; fullName: string; enCode?: string }> }>('/system/DataSource')
const list = r.data?.list || []
if (Array.isArray(list) && list.length > 0) {
// 优先匹 appCode 同名, 其次任何非平台库
const byApp = list.find((d) => d.fullName === this.appCode || d.enCode === this.appCode)
const fallback = list.find((d) => d.id && d.id !== '0')
const biz = byApp || fallback
if (biz) this.dbLinkId = biz.id
}
} catch (e) {
log.debug('detectDbLinkId failed:', (e as Error).message)
}
}
persist(): void {
const t: TokenFile = {
baseUrl: this.baseUrl,
appCode: this.appCode,
account: this.account,
token: this.token,
loginAt: new Date().toISOString(),
dbLinkId: this.dbLinkId,
}
saveToken(t)
}
// ----- HTTP -----
async get<T = unknown>(path: string, query?: Record<string, string | number | undefined>): Promise<JnpfResp<T>> {
let url = `${this.baseUrl}${path}`
if (query) {
const cleaned: Record<string, string> = {}
for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null) cleaned[k] = String(v)
const qs = new URLSearchParams(cleaned).toString()
if (qs) url += `?${qs}`
}
log.debug('GET', url)
const res = await fetch(url, { method: 'GET', headers: this.headers() })
return parseJson<T>(await res.text())
}
async postJson<T = unknown>(path: string, body: unknown): Promise<JnpfResp<T>> {
log.debug('POST', this.baseUrl + path)
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'POST',
headers: this.headers(),
body: JSON.stringify(body),
})
return parseJson<T>(await res.text())
}
async putJson<T = unknown>(path: string, body: unknown): Promise<JnpfResp<T>> {
log.debug('PUT', this.baseUrl + path)
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'PUT',
headers: this.headers(),
body: JSON.stringify(body),
})
return parseJson<T>(await res.text())
}
async del<T = unknown>(path: string): Promise<JnpfResp<T>> {
log.debug('DELETE', this.baseUrl + path)
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'DELETE',
headers: this.headers(),
})
return parseJson<T>(await res.text())
}
/** 业务码非 200 直接抛 */
ok<T>(r: JnpfResp<T>): T {
if (r.code !== 200) throw new DacliError(`API code=${r.code}: ${r.msg}`, r.code, JSON.stringify(r))
return r.data as T
}
private headers(): Record<string, string> {
return {
'Content-Type': 'application/json',
Authorization: this.token,
'App-Code': this.appCode,
}
}
}
function parseJson<T>(text: string): JnpfResp<T> {
try {
return JSON.parse(text) as JnpfResp<T>
} catch {
return { code: -1, msg: `JSON parse error: ${text.slice(0, 200)}`, data: null }
}
}
+68
View File
@@ -0,0 +1,68 @@
/**
* config.ts — token / baseUrl / appCode 持久化
*
* 路径: $DACLI_TOKEN_DIR/token.json 或 ./.dacli-token/token.json
*
* 与 Java 版兼容: 路径写在 cwd 下 (CLAUDE.md "$ccWorkDir/.dacli-token/token.json")
* 但 TS 版只管 $ccWorkDir/dacli 自己, 不动 Java 版的 token (Java 版已废弃归档)。
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import type { TokenFile } from './types.ts'
const DEFAULT_BASE_URL = process.env.JNPF_BASE_URL || 'http://nginx/api'
function tokenDir(): string {
if (process.env.DACLI_TOKEN_DIR) return resolve(process.env.DACLI_TOKEN_DIR)
return resolve(process.cwd(), '.dacli-token')
}
function tokenPath(): string {
return join(tokenDir(), 'token.json')
}
export function getTokenPath(): string {
return tokenPath()
}
export function loadToken(): TokenFile | null {
const p = tokenPath()
if (!existsSync(p)) return null
try {
return JSON.parse(readFileSync(p, 'utf-8')) as TokenFile
} catch {
return null
}
}
export function saveToken(t: TokenFile): void {
const dir = tokenDir()
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
writeFileSync(tokenPath(), JSON.stringify(t, null, 2), 'utf-8')
}
export function clearToken(): void {
const p = tokenPath()
if (existsSync(p)) rmSync(p)
}
/** 当前 baseUrl (优先 env, 然后 token, 然后默认) */
export function currentBaseUrl(): string {
const t = loadToken()
return process.env.JNPF_BASE_URL || t?.baseUrl || DEFAULT_BASE_URL
}
/** 默认凭据 (供 login 默认值用) */
export const DEFAULT_ACCOUNT = process.env.JNPF_ACCOUNT || 'admin'
export const DEFAULT_PASSWORD = process.env.JNPF_PASSWORD || '123456'
export const DEFAULT_APP_CODE = process.env.JNPF_APP_CODE || 'developSystem'
/** baseUrl 兜底列表 (按优先级) */
export function baseUrlCandidates(): string[] {
const list = [
process.env.JNPF_BASE_URL,
'http://nginx/api',
'http://127.0.0.1:30000/api',
].filter(Boolean) as string[]
return Array.from(new Set(list))
}
+78
View File
@@ -0,0 +1,78 @@
/**
* crypto.ts — 严格 1:1 复刻 web cipher.ts (字节级一致)
*
* 流程: 明文 → md5(hex) → AES-ECB-Pkcs7(key=md5(VITE_CIPHER_KEY)) → Base64 → Hex
*
* 关键: cipher.ts:34-37 `Hex.stringify(Base64.parse(result))` 是对 Base64 字符串做 hex,
* 不是对密文字节做 hex。这是 ddcc 实验里踩过的最大坑。
*
* 输入 '123456' 应输出 96 字符 hex (与 web 一致)。
*/
import CryptoJS from 'crypto-js'
import { existsSync, readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
/** 默认密钥来自 web .env VITE_CIPHER_KEY */
const FALLBACK_KEY = 'EY8WePvjM5GGwQzn'
let _cipherKey: string | null = null
function loadCipherKey(): string {
if (_cipherKey) return _cipherKey
if (process.env.VITE_CIPHER_KEY) {
_cipherKey = process.env.VITE_CIPHER_KEY
return _cipherKey
}
try {
const here = dirname(fileURLToPath(import.meta.url))
const candidates = [
resolve(here, '../../../../web/apps/jnpf-web-apps-main/.env'),
resolve(here, '../../../web/apps/jnpf-web-apps-main/.env'),
resolve(here, '../../web/apps/jnpf-web-apps-main/.env'),
]
for (const p of candidates) {
if (existsSync(p)) {
const m = readFileSync(p, 'utf-8').match(/VITE_CIPHER_KEY\s*=\s*(\S+)/)
if (m) {
_cipherKey = m[1]
return _cipherKey
}
}
}
} catch {
/* ignore — fallback */
}
_cipherKey = FALLBACK_KEY
return _cipherKey
}
export function encryptByMd5(plain: string): string {
return CryptoJS.MD5(plain).toString()
}
/** AES-ECB-Pkcs7(密钥=md5(CIPHER_KEY)),再 Base64→Hex */
function aesEcbHex(inputHex: string): string {
const aesKey = encryptByMd5(loadCipherKey())
const encrypted = CryptoJS.AES.encrypt(
inputHex,
CryptoJS.enc.Utf8.parse(aesKey),
{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 },
)
const base64 = encrypted.toString()
// 注意: 是对 base64 字符串做 hex (web cipher.ts:36)
return CryptoJS.enc.Hex.stringify(CryptoJS.enc.Base64.parse(base64))
}
/**
* 完整登录加密 (与 LoginForm.handleLogin 一致):
* md5(plain) → aesEncryption.encryptByAES(md5Hex)
*/
export function encryptPassword(plain: string): string {
return aesEcbHex(encryptByMd5(plain))
}
/** 96 字符的 hex 即认为已加密 */
export function isEncrypted(p: string | undefined | null): boolean {
return !!p && p.length === 96 && /^[0-9a-f]+$/i.test(p)
}
+111
View File
@@ -0,0 +1,111 @@
/**
* help.ts — AI 友好帮助体系
*
* 用法: 给 Commander.js 命令对象挂元数据 (cmd as any)._aiMeta = meta
* 由 cli.ts 顶层在 parse 之前扫 argv 拦截 --ai-help / --example / --source
* 打印后 process.exit, 避免命令真正执行 / 校验 requiredOption
*/
import type { Command } from 'commander'
export interface AiHelp {
purpose: string
required?: Record<string, string>
optional?: Record<string, string>
example?: string | string[]
source?: { web?: string; api?: string; ref?: string }
notes?: string[]
}
const AI_FLAGS = new Set(['--ai-help', '--example', '--source'])
/** 把元数据挂到 command 上, cli.ts 顶层会读 */
export function installAiHelpHook(cmd: Command, meta: AiHelp): void {
;(cmd as unknown as { _aiMeta?: AiHelp })._aiMeta = meta
}
function getMeta(cmd: Command): AiHelp | undefined {
return (cmd as unknown as { _aiMeta?: AiHelp })._aiMeta
}
/**
* 顶层在 parse 前调用. 命中 ai flag 则打印 + exit, 返回 true.
*/
export function maybeInterceptAiHelp(program: Command): boolean {
const argv = process.argv.slice(2)
const flagIdx = argv.findIndex((a) => AI_FLAGS.has(a))
if (flagIdx < 0) return false
const flag = argv[flagIdx]
// 把 flag 之前的非选项 token 当成命令路径
const path = argv.slice(0, flagIdx).filter((a) => !a.startsWith('-'))
// 走命令树
let cur: Command = program
for (const p of path) {
const sub = cur.commands.find((c) => c.name() === p)
if (!sub) break
cur = sub
}
const meta = getMeta(cur)
if (!meta) {
console.error(`(no ai-help for: ${path.join(' ') || '<root>'})`)
process.exit(2)
}
if (flag === '--example') {
const ex = Array.isArray(meta.example) ? meta.example.join('\n') : meta.example || '(no example)'
console.log(ex)
} else if (flag === '--source') {
const lines: string[] = []
if (meta.source?.web) lines.push(`web: ${meta.source.web}`)
if (meta.source?.api) lines.push(`api: ${meta.source.api}`)
console.log(lines.join('\n') || '(no source)')
} else {
console.log(renderAiHelp(cur, meta))
}
process.exit(0)
}
function renderAiHelp(cmd: Command, meta: AiHelp): string {
const lines: string[] = []
// 拼出完整路径
const path: string[] = [cmd.name()]
let p: Command | null = cmd.parent as Command | null
while (p) {
path.unshift(p.name())
p = p.parent as Command | null
}
// 去 root 名
const fullCmd = path.slice(1).join(' ') || path[0]
lines.push(`# dacli ${fullCmd}`)
lines.push('')
lines.push('## 用途')
lines.push(meta.purpose)
if (meta.required && Object.keys(meta.required).length) {
lines.push('')
lines.push('## 必传参数')
for (const [k, v] of Object.entries(meta.required)) lines.push(`- \`${k}\`: ${v}`)
}
if (meta.optional && Object.keys(meta.optional).length) {
lines.push('')
lines.push('## 可选参数')
for (const [k, v] of Object.entries(meta.optional)) lines.push(`- \`${k}\`: ${v}`)
}
if (meta.source?.web || meta.source?.api) {
lines.push('')
lines.push('## 来源')
if (meta.source.web) lines.push(`- web 源码: ${meta.source.web}`)
if (meta.source.api) lines.push(`- API: ${meta.source.api}`)
}
if (meta.example) {
lines.push('')
lines.push('## 例子')
lines.push('```bash')
lines.push(Array.isArray(meta.example) ? meta.example.join('\n') : meta.example)
lines.push('```')
}
if (meta.notes && meta.notes.length) {
lines.push('')
lines.push('## 注意')
for (const n of meta.notes) lines.push(`- ${n}`)
}
return lines.join('\n')
}
+44
View File
@@ -0,0 +1,44 @@
/**
* log.ts — 极简彩色日志
*/
const isTTY = process.stdout.isTTY
const C = {
reset: isTTY ? '\x1b[0m' : '',
dim: isTTY ? '\x1b[2m' : '',
red: isTTY ? '\x1b[31m' : '',
green: isTTY ? '\x1b[32m' : '',
yellow: isTTY ? '\x1b[33m' : '',
blue: isTTY ? '\x1b[34m' : '',
cyan: isTTY ? '\x1b[36m' : '',
bold: isTTY ? '\x1b[1m' : '',
}
export const log = {
info(...args: unknown[]) {
console.log(`${C.cyan}ℹ${C.reset}`, ...args)
},
ok(...args: unknown[]) {
console.log(`${C.green}✓${C.reset}`, ...args)
},
warn(...args: unknown[]) {
console.warn(`${C.yellow}!${C.reset}`, ...args)
},
error(...args: unknown[]) {
console.error(`${C.red}✗${C.reset}`, ...args)
},
dim(...args: unknown[]) {
console.log(`${C.dim}${args.join(' ')}${C.reset}`)
},
raw(s: string) {
process.stdout.write(s)
},
/** 仅在 DACLI_DEBUG=1 时打 */
debug(...args: unknown[]) {
if (process.env.DACLI_DEBUG === '1') console.error(`${C.dim}[debug]${C.reset}`, ...args)
},
}
/** JSON 美化输出 (供命令直接打到 stdout, 便于 jq 管道) */
export function printJson(v: unknown): void {
console.log(JSON.stringify(v, null, 2))
}
+66
View File
@@ -0,0 +1,66 @@
/**
* types.ts — 共享类型定义
*/
export interface JnpfResp<T = unknown> {
code: number
msg: string
data: T | null
}
export interface DataSourceMeta {
id: string
fullName: string
enCode: string
dbType: string
}
export interface LoginResp {
token: string
theme?: string
isSaas?: boolean
}
export interface TokenFile {
baseUrl: string
appCode: string
account: string
token: string
/** ISO 时间, token 7 天过期 */
loginAt: string
/** 业务库 id (从 /system/DataSource 取第一个非主库) */
dbLinkId?: string
}
export interface FormSummary {
id: string
fullName: string
enCode: string
state: number
type: number
webType: number
dbLinkId?: string
category?: string
creatorTime?: string
}
export interface FormDetail extends FormSummary {
formData?: unknown
columnData?: unknown
tables?: unknown[]
[k: string]: unknown
}
/**
* dacli 内部错误 (包装 HTTP 业务码 != 200)
*/
export class DacliError extends Error {
code: number
raw?: string
constructor(message: string, code = -1, raw?: string) {
super(message)
this.name = 'DacliError'
this.code = code
this.raw = raw
}
}
View File
Whitespace-only changes.
+267
View File
@@ -0,0 +1,267 @@
/**
* schema/FieldBuilder.ts — 通用 FieldBuilder
*
* 从 src/data/*.json 加载 schema, 暴露 `build(jnpfKey, props)` API.
*
* 核心设计 (来自 doc/architecture.md §2.3):
* - 不用 Java 版 53 个硬编码 builder
* - 1 个通用 builder + JSON schema
* - JNPF 升级: 重跑 extract-all, 不改 builder 代码
*
* 数据流:
* component-map.json (jnpfKey → tag) ─┐
* field-schemas.json (jnpfKey → fields) ─┤→ FieldBuilder.build()
* validation-rules.json (L1 正则) ─┘
*
* 用法:
* const fb = new FieldBuilder()
* const f = fb.build('input', { label: '姓名', __config__: { required: true } })
*/
import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
// ----- JSON 数据类型 -----
export interface ComponentMap {
[jnpfKey: string]: string
}
export interface FieldSchemas {
[jnpfKey: string]: string[]
}
export interface ValidationRule {
msg: string
rule: string
}
export interface ValidationRules {
[name: string]: ValidationRule
}
// ----- 加载工具 -----
function dataDir(): string {
// 文件位置: src/schema/FieldBuilder.ts
// 数据位置: src/data/*.json
// __dirname = src/schema → ../../data ? No: src/schema → ../data
const here = dirname(fileURLToPath(import.meta.url))
return resolve(here, '../data')
}
function readJson<T>(file: string): T {
const p = resolve(dataDir(), file)
return JSON.parse(readFileSync(p, 'utf-8')) as T
}
/** 加载 component-map (jnpfKey → tag). 60+ 项 */
export function loadComponentMap(): ComponentMap {
return readJson<ComponentMap>('component-map.json')
}
/** 加载 field-schemas (jnpfKey → activeData 字段列表). 39 控件 */
export function loadFieldSchemas(): FieldSchemas {
return readJson<FieldSchemas>('field-schemas.json')
}
/** 加载 validation-rules (L1 正则). 14 条 */
export function loadValidationRules(): ValidationRules {
return readJson<ValidationRules>('validation-rules.json')
}
// ----- 通用 FieldBuilder -----
/** 完整 field 形状 (来自 web componentMap.ts 的 inputComponents 之一) */
export interface JnpfField {
__config__: {
jnpfKey: string
label: string
tag: string
span: number
layout: 'colFormItem' | 'rowFormItem'
showLabel: boolean
required: boolean
regList: unknown[]
trigger: string | string[]
visibility: string[]
[k: string]: unknown
}
// 其他属性 (placeholder, style, options 等) 由用户传入
[k: string]: unknown
}
/** 控件分类 (来自 web componentMap.ts) */
export const COMPONENT_CATEGORY: Record<string, 'input' | 'select' | 'system' | 'layout' | 'ocr'> = {
// 基础 input
input: 'input', textarea: 'input', inputNumber: 'input', switch: 'input',
radio: 'input', checkbox: 'input', select: 'input', cascader: 'input',
datePicker: 'input', timePicker: 'input', uploadFile: 'input', uploadImg: 'input',
colorPicker: 'input', rate: 'input', slider: 'input', editor: 'input',
link: 'input', button: 'input', text: 'input', alert: 'input',
qrcode: 'input', barcode: 'input', carousel: 'input',
// 高级 select
organizeSelect: 'select', posSelect: 'select', userSelect: 'select',
roleSelect: 'select', groupSelect: 'select', table: 'select',
treeSelect: 'select', popupTableSelect: 'select', autoComplete: 'select',
areaSelect: 'select', relationForm: 'select', relationFormAttr: 'select',
popupSelect: 'select', popupAttr: 'select', signature: 'select',
sign: 'select', location: 'select', iframe: 'select', calculate: 'select',
dateCalculate: 'select', relationQuery: 'select',
// 系统
createUser: 'system', createTime: 'system', modifyUser: 'system',
modifyTime: 'system', currOrganize: 'system', currPosition: 'system', billRule: 'system',
// 布局
groupTitle: 'layout', divider: 'layout', collapse: 'layout', tab: 'layout',
steps: 'layout', row: 'layout', card: 'layout', tableGrid: 'layout',
}
/** layout 类的 jnpfKey */
const LAYOUT_KEYS = new Set([
'groupTitle', 'divider', 'collapse', 'tab', 'steps', 'row', 'card', 'tableGrid',
])
/** 子表 (table) 类 (特殊) */
const TABLE_KEY = 'table'
/**
* 通用 FieldBuilder — 从 JSON schema 装配一个完整 field
*
* @param jnpfKey 控件 key (e.g. 'input', 'select', 'relationForm')
* @param props 覆盖属性, 可含 __config__ 子对象覆盖默认
* @returns 完整 JnpfField 对象
*/
export class FieldBuilder {
private componentMap: ComponentMap
private fieldSchemas: FieldSchemas
private validationRules: ValidationRules
constructor() {
this.componentMap = loadComponentMap()
this.fieldSchemas = loadFieldSchemas()
this.validationRules = loadValidationRules()
}
/** 所有已知的 jnpfKey */
listKeys(): string[] {
return Object.keys(this.componentMap)
}
/** 控件分类 */
category(jnpfKey: string): 'input' | 'select' | 'system' | 'layout' | 'ocr' | 'unknown' {
return COMPONENT_CATEGORY[jnpfKey] || 'unknown'
}
/** jnpfKey 对应的 tag (e.g. 'input' → 'JnpfInput'). 找不到返回 undefined */
tag(jnpfKey: string): string | undefined {
return this.componentMap[jnpfKey]
}
/** 控件在 Rxxx.vue 里实际使用的 activeData 字段列表 (来自 field-schemas.json) */
activeDataFields(jnpfKey: string): string[] {
return this.fieldSchemas[jnpfKey] || []
}
/** L1 正则规则 (14 条) */
validationRule(name: string): ValidationRule | undefined {
return this.validationRules[name]
}
/** 所有 L1 正则 key (供 `dacli form create --fields` 用) */
validationRuleKeys(): string[] {
return Object.keys(this.validationRules)
}
/**
* 构造一个完整 field 对象.
*
* @example
* const f = fb.build('input', {
* label: '姓名',
* __config__: { required: true, regList: [{ pattern: 'chinese', message: '请输入中文' }] },
* placeholder: '请输入姓名',
* })
*/
build(jnpfKey: string, props: Record<string, unknown> = {}): JnpfField {
const tag = this.componentMap[jnpfKey]
if (!tag) {
throw new Error(`Unknown jnpfKey: '${jnpfKey}'. 可用: ${this.listKeys().slice(0, 10).join(', ')}...`)
}
const cat = this.category(jnpfKey)
const isLayout = cat === 'layout'
const isTable = jnpfKey === TABLE_KEY
// 默认 __config__
const defaultConfig: Record<string, unknown> = {
jnpfKey,
label: props.label as string || jnpfKey,
tag,
showLabel: !isLayout,
span: 24,
layout: isLayout || isTable ? 'rowFormItem' : 'colFormItem',
required: false,
visibility: ['pc', 'app'],
noShow: false,
dragDisabled: false,
}
// 大部分控件有 regList, 简单系统/布局类没有
if (!isLayout && jnpfKey !== 'billRule' && jnpfKey !== 'createUser' && jnpfKey !== 'createTime' &&
jnpfKey !== 'modifyUser' && jnpfKey !== 'modifyTime' && jnpfKey !== 'currOrganize' &&
jnpfKey !== 'currPosition' && jnpfKey !== 'link' && jnpfKey !== 'button' && jnpfKey !== 'text' &&
jnpfKey !== 'alert' && jnpfKey !== 'iframe') {
defaultConfig.regList = []
}
// trigger
if (['input', 'textarea'].includes(jnpfKey)) defaultConfig.trigger = 'blur'
else if (['switch', 'radio', 'checkbox', 'select', 'cascader', 'datePicker', 'timePicker',
'uploadFile', 'uploadImg', 'colorPicker', 'rate', 'slider', 'treeSelect',
'popupTableSelect', 'areaSelect', 'relationForm', 'popupSelect', 'signature',
'sign', 'location', 'userSelect', 'roleSelect', 'organizeSelect', 'posSelect',
'groupSelect', 'inputNumber', 'autoComplete'].includes(jnpfKey)) {
defaultConfig.trigger = 'change'
}
else if (jnpfKey === 'editor') defaultConfig.trigger = 'blur'
// 合并 __config__ (用户提供优先)
const userConfig = (props.__config__ as Record<string, unknown>) || {}
const finalConfig: Record<string, unknown> = { ...defaultConfig, ...userConfig }
// label 一致性: __config__.label 优先 (用户可能两边都传)
if (props.label && !userConfig.label) finalConfig.label = props.label
// 默认属性 (style 等)
const defaults: Record<string, unknown> = {
style: { width: '100%' },
}
// switch/radio/checkbox/select 默认值
if (jnpfKey === 'switch') defaults.defaultValue = 0
if (jnpfKey === 'checkbox') defaults.defaultValue = []
if (jnpfKey === 'cascader') defaults.defaultValue = []
if (jnpfKey === 'rate' || jnpfKey === 'slider') defaults.defaultValue = 0
const { __config__: _drop, ...restUser } = props
return {
...defaults,
...restUser,
__config__: finalConfig,
} as JnpfField
}
/**
* 便利: 构造 regList 条目 (引用 L1 正则).
* @example
* fb.regList('chinese', '请输入中文')
* → { pattern: 'chinese', message: '请输入中文' }
*/
regList(name: string, customMsg?: string): { pattern: string; message: string } {
const r = this.validationRules[name]
if (!r) throw new Error(`Unknown L1 rule: '${name}'. 可用: ${this.validationRuleKeys().join(', ')}`)
return { pattern: name, message: customMsg || r.msg }
}
}
/** 全局单例 (复用已加载的 JSON) */
let _defaultBuilder: FieldBuilder | null = null
export function defaultFieldBuilder(): FieldBuilder {
if (!_defaultBuilder) _defaultBuilder = new FieldBuilder()
return _defaultBuilder
}
+10
View File
@@ -0,0 +1,10 @@
/**
* schema/index.ts — FieldBuilder 入口
*
* 用法:
* import { FieldBuilder, defaultFieldBuilder, type JnpfField } from '../schema/index.ts'
*
* const fb = defaultFieldBuilder()
* const field = fb.build('input', { label: '姓名', __config__: { required: true } })
*/
export * from './FieldBuilder.ts'