import { writeFileSync } from "node:fs"; import { VERSION } from "../version.js"; import type { OutputOptions } from "./types.js"; export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000; export function redactSensitiveText(value: string): string { return value .replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1") .replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1") .replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1"); } export function protectLargeOutput(result: unknown, options: OutputOptions = {}) { if (options.allowFull || options.outputFile) return; const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) { throw new Error( `输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。` ); } } export function printJson(data: unknown, options: OutputOptions = {}): string { protectLargeOutput(data, options); const json = JSON.stringify(data, null, 2); if (options.outputFile) { writeFileSync(options.outputFile, json, "utf-8"); return JSON.stringify( { outputFile: options.outputFile, bytes: Buffer.byteLength(json, "utf-8"), }, null, 2 ); } return json; } export function formatSourceLabel(source?: string): string { switch (source) { case "assist": return "官方协助/代客平台 (Assist Platform)"; case "account": return "统一认证中心 (IDP 账密/短信)"; case "browser": return "浏览器会话同步 (WebBridge)"; case "curl": case "f12": return "cURL 抓包导入 (cURL/F12)"; case "manual": return "手动配置"; default: return source || "未知来源"; } } export function formatExpiresAt(expiresAt?: number): string { if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制"; const diffMs = expiresAt - Date.now(); const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false }); if (diffMs <= 0) { return `${dateStr} (⚠️ 已过期)`; } const diffMins = Math.floor(diffMs / 60000); if (diffMins < 60) { return `${dateStr} (约剩余 ${diffMins} 分钟)`; } const diffHours = (diffMs / 3600000).toFixed(1); if (Number(diffHours) < 24) { return `${dateStr} (约剩余 ${diffHours} 小时)`; } const diffDays = Math.floor(diffMs / 86400000); return `${dateStr} (约剩余 ${diffDays} 天)`; } export function printKeyValue(pairs: Record): string { const lines: string[] = []; const maxKeyLen = Math.max(...Object.keys(pairs).map((k) => k.length), 0); for (const [key, val] of Object.entries(pairs)) { const formattedVal = typeof val === "object" ? JSON.stringify(val) : String(val ?? ""); lines.push(` ${key.padEnd(maxKeyLen + 2)}: ${formattedVal}`); } return lines.join("\n"); } export function printTable( headers: string[], rows: Array> ): string { if (rows.length === 0) return " (暂无数据)\n"; const strRows = rows.map((r) => r.map((c) => String(c ?? ""))); const colWidths = headers.map((h, colIdx) => { const maxRowWidth = Math.max(...strRows.map((r) => (r[colIdx] || "").length), 0); return Math.max(h.length, maxRowWidth); }); const headerLine = headers.map((h, i) => h.padEnd(colWidths[i])).join(" "); const separatorLine = colWidths.map((w) => "-".repeat(w)).join(" "); const dataLines = strRows.map((r) => r.map((c, i) => c.padEnd(colWidths[i])).join(" ") ); return [headerLine, separatorLine, ...dataLines].map((l) => ` ${l}`).join("\n"); } export function printHelp(): string { return ` 合思/易快报企业级 CLI 工具 (hose-use) v${VERSION} 用法: hose-use <命令域> <子命令> [参数] [选项] 核心命令域: auth 认证与凭证管理 (login, status, refresh, import, accounts) corps 多企业租户管理 (list, switch, current) config 全局运行模式与路径诊断 (show, paths, mode , set) workflow 工作流管理 (list, get, find, analyze, toggle) bill 单据与费用明细检索 (list, get <单号|ID>, refs <单号|ID>, relations <单号|ID>, attachments <单号|ID>, flow <单号|ID>, risk <单号|ID>, budget <单号|ID>, schema, link <单号|ID>) contact 企业通讯录与人员检索 (list, search <关键词>, get ) task 待办中心与审批任务 (todo, approved, records, submitted, cc) message 消息中心与通知管理 (list, count, read, read-all) platform 自建应用管理 (list) dimension 系统/自定义档案维度 (list, items <维度>) role 角色定义与成员 (list, groups, members <角色>) skill Agent Skill 管理 (install, status, dump) probe 连通性诊断 (probe [corpId]) update 版本自更新与发布记录 (update, update check, update --changelog) openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info) http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1]) service 常驻守护进程管理 (service start|stop|restart|status|logs) mcp MCP Server 运行 (serve) version 查看版本信息 全局选项: --corp= 临时指定操作的企业/身份 ID (覆盖默认企业) --json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成) --output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要 --full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截) --stateless 单次强制以无状态模式执行 --stateful 单次强制以有状态模式执行 --help, -h 查看帮助信息 常用示例: hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录 hose-use auth status # 查看当前登录状态与活跃企业 hose-use config paths # 查看多级企业配置目录链 hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作) hose-use corps list # 列出名下所有企业 hose-use corps switch ID01MCcOgJl1td # 切换工作企业 hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话 hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护) hose-use task todo --json # 查看当前待我审批任务 hose-use task approved # 查看我已审批任务 hose-use task submitted # 查看我发起的单据 hose-use task cc --unread # 查看未读抄送 hose-use message list --unread # 查看未读消息 hose-use message count # 查看未读消息数 hose-use workflow list # 汇总查看全部工作流 hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流 hose-use bill list # 查看当前企业单据与报销列表 hose-use bill flow S26000001 # 查看单据审批历史与后续节点 hose-use bill risk S26000001 # 查看风控预警、预算与发票风险 hose-use bill refs S26000001 # 二级解析提交人、部门、法人实体与费用类型引用 hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联 hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态 hose-use bill attachments S26000001 # 查看单据附件和发票原件标准列表 hose-use dimension list # 查看系统与自定义档案维度 hose-use dimension items 项目 # 查看项目档案项 hose-use role list # 查看企业角色定义 hose-use role groups # 查看角色组及其角色 hose-use role members 财务主管 # 查看指定角色成员 hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接 hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆 hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情 hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档 hose-use service start # 后台启动常驻守护进程服务 hose-use service status # 查看守护进程运行状态与接口地址 hose-use probe # 诊断当前企业鉴权连通性 hose-use skill install # 安装 Agent 技能到用户目录 hose-use update # 自动检查并升级到最新版本 hose-use update --changelog # 查看版本发布历史 hose-use openapi paths # 查看所有 API 路径与概要一览 hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范 `.trim(); }