@lark-apaas/miaoda-cli 0.1.3-alpha.4bf312e → 0.1.3-alpha.4ec3549

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/api/app/api.js +3 -3
  2. package/dist/api/app/schemas.js +43 -43
  3. package/dist/api/db/api.js +132 -112
  4. package/dist/api/db/client.js +41 -41
  5. package/dist/api/db/index.js +2 -1
  6. package/dist/api/db/parsers.js +20 -20
  7. package/dist/api/db/sql-keywords.js +87 -87
  8. package/dist/api/deploy/api.js +5 -5
  9. package/dist/api/deploy/schemas.js +32 -32
  10. package/dist/api/file/api.js +74 -87
  11. package/dist/api/file/client.js +62 -22
  12. package/dist/api/file/detect.js +3 -3
  13. package/dist/api/file/parsers.js +18 -7
  14. package/dist/api/observability/api.js +6 -6
  15. package/dist/api/observability/schemas.js +14 -14
  16. package/dist/api/plugin/api.js +31 -31
  17. package/dist/cli/commands/app/index.js +12 -12
  18. package/dist/cli/commands/db/index.js +268 -163
  19. package/dist/cli/commands/deploy/index.js +28 -28
  20. package/dist/cli/commands/file/index.js +81 -61
  21. package/dist/cli/commands/observability/index.js +69 -69
  22. package/dist/cli/commands/plugin/index.js +27 -27
  23. package/dist/cli/commands/shared.js +10 -10
  24. package/dist/cli/handlers/app/update.js +2 -2
  25. package/dist/cli/handlers/db/_operator.js +35 -0
  26. package/dist/cli/handlers/db/audit.js +104 -53
  27. package/dist/cli/handlers/db/changelog.js +28 -13
  28. package/dist/cli/handlers/db/data.js +31 -30
  29. package/dist/cli/handlers/db/migration.js +27 -27
  30. package/dist/cli/handlers/db/quota.js +3 -3
  31. package/dist/cli/handlers/db/recovery.js +138 -98
  32. package/dist/cli/handlers/db/schema.js +33 -33
  33. package/dist/cli/handlers/db/sql.js +69 -69
  34. package/dist/cli/handlers/deploy/deploy.js +4 -4
  35. package/dist/cli/handlers/deploy/error-log.js +1 -1
  36. package/dist/cli/handlers/deploy/get.js +3 -3
  37. package/dist/cli/handlers/deploy/polling.js +11 -11
  38. package/dist/cli/handlers/file/cp.js +30 -30
  39. package/dist/cli/handlers/file/ls.js +5 -5
  40. package/dist/cli/handlers/file/quota.js +2 -2
  41. package/dist/cli/handlers/file/rm.js +24 -24
  42. package/dist/cli/handlers/file/sign.js +3 -3
  43. package/dist/cli/handlers/file/stat.js +10 -9
  44. package/dist/cli/handlers/observability/analytics.js +47 -47
  45. package/dist/cli/handlers/observability/helpers.js +2 -2
  46. package/dist/cli/handlers/observability/log.js +9 -9
  47. package/dist/cli/handlers/observability/metric.js +26 -26
  48. package/dist/cli/handlers/observability/trace.js +5 -5
  49. package/dist/cli/handlers/plugin/plugin-local.js +53 -53
  50. package/dist/cli/handlers/plugin/plugin.js +15 -15
  51. package/dist/cli/help.js +16 -16
  52. package/dist/main.js +12 -12
  53. package/dist/utils/args.js +1 -1
  54. package/dist/utils/colors.js +2 -2
  55. package/dist/utils/config.js +2 -2
  56. package/dist/utils/devops-error.js +9 -9
  57. package/dist/utils/error.js +2 -2
  58. package/dist/utils/git.js +4 -4
  59. package/dist/utils/http.js +19 -19
  60. package/dist/utils/output.js +47 -47
  61. package/dist/utils/poll.js +2 -2
  62. package/dist/utils/render.js +27 -27
  63. package/dist/utils/time.js +47 -42
  64. package/package.json +1 -1
@@ -4,13 +4,13 @@ exports.registerPluginCommands = registerPluginCommands;
4
4
  const index_1 = require("../../../cli/handlers/plugin/index");
5
5
  function registerPluginCommands(program) {
6
6
  const pluginCmd = program
7
- .command("plugin")
8
- .description("插件管理:安装/更新/移除插件包,查询 capability 实例")
9
- .usage("<command> [flags]");
7
+ .command('plugin')
8
+ .description('插件管理:安装/更新/移除插件包,查询 capability 实例')
9
+ .usage('<command> [flags]');
10
10
  pluginCmd.action(() => {
11
11
  pluginCmd.outputHelp();
12
12
  });
13
- pluginCmd.addHelpText("after", `
13
+ pluginCmd.addHelpText('after', `
14
14
  概念
15
15
  - 插件包 (plugin package):.tgz 包,释放到 ./node_modules/<name>
16
16
  - actionPlugins:./package.json 里的字段,记录 { "@scope/name": "version" },作为
@@ -26,10 +26,10 @@ function registerPluginCommands(program) {
26
26
  - remove / list / list-packages:纯本地 FS,不走网络
27
27
  `);
28
28
  pluginCmd
29
- .command("install")
30
- .description("拉取插件包并安装到当前应用项目")
31
- .argument("<names...>", "插件名,格式 @scope/name 或 @scope/name@version;未带版本默认 latest")
32
- .addHelpText("after", `
29
+ .command('install')
30
+ .description('拉取插件包并安装到当前应用项目')
31
+ .argument('<names...>', '插件名,格式 @scope/name 或 @scope/name@version;未带版本默认 latest')
32
+ .addHelpText('after', `
33
33
  行为
34
34
  - 拉取 .tgz 到本地缓存,解压到 ./node_modules/<name>
35
35
  - 在 ./package.json 的 actionPlugins 字段记录 <name>: <version>
@@ -62,10 +62,10 @@ JSON 输出
62
62
  await (0, index_1.handlePluginInstall)({ names });
63
63
  });
64
64
  pluginCmd
65
- .command("update")
66
- .description("把已安装插件升级到 latest 版本")
67
- .argument("<names...>", "插件名,格式 @scope/name;带 @version 也只取 name 部分")
68
- .addHelpText("after", `
65
+ .command('update')
66
+ .description('把已安装插件升级到 latest 版本')
67
+ .argument('<names...>', '插件名,格式 @scope/name;带 @version 也只取 name 部分')
68
+ .addHelpText('after', `
69
69
  行为
70
70
  - 仅对已在 actionPlugins 里的插件生效;未安装的插件返回 notInstalled
71
71
  - 拉取 latest 版本 .tgz,覆盖安装到 ./node_modules/<name>
@@ -97,10 +97,10 @@ JSON 输出
97
97
  await (0, index_1.handlePluginUpdate)({ names });
98
98
  });
99
99
  pluginCmd
100
- .command("remove")
101
- .description("从当前项目移除一个已安装的插件")
102
- .argument("<name>", "插件名,格式 @scope/name")
103
- .addHelpText("after", `
100
+ .command('remove')
101
+ .description('从当前项目移除一个已安装的插件')
102
+ .argument('<name>', '插件名,格式 @scope/name')
103
+ .addHelpText('after', `
104
104
  行为
105
105
  - 删除 ./node_modules/<name> 目录
106
106
  - 从 ./package.json 的 actionPlugins 字段移除对应条目
@@ -123,9 +123,9 @@ JSON 输出
123
123
  (0, index_1.handlePluginRemove)({ name });
124
124
  });
125
125
  pluginCmd
126
- .command("init")
127
- .description("按 package.json 的 actionPlugins 批量安装所有插件")
128
- .addHelpText("after", `
126
+ .command('init')
127
+ .description('按 package.json 的 actionPlugins 批量安装所有插件')
128
+ .addHelpText('after', `
129
129
  行为
130
130
  - 读取 ./package.json 的 actionPlugins,对每个条目按固定版本安装
131
131
  - 已经是目标版本的跳过(幂等),用于 clone 项目后首次同步 / CI
@@ -156,11 +156,11 @@ JSON 输出
156
156
  await (0, index_1.handlePluginInit)();
157
157
  });
158
158
  pluginCmd
159
- .command("list")
160
- .description("列出当前项目的 capability 实例(./server/capabilities/*.json)")
161
- .option("--summary", "不 hydrate(不充血),直接返回 capability 文件的原始 JSON")
162
- .option("--id <id>", "只查询指定 id 的单个 capability")
163
- .addHelpText("after", `
159
+ .command('list')
160
+ .description('列出当前项目的 capability 实例(./server/capabilities/*.json)')
161
+ .option('--summary', '不 hydrate(不充血),直接返回 capability 文件的原始 JSON')
162
+ .option('--id <id>', '只查询指定 id 的单个 capability')
163
+ .addHelpText('after', `
164
164
  行为
165
165
  - 扫描 ./server/capabilities/*.json(排除 capabilities.json)
166
166
  - 默认对每条 capability 做 hydrate:读取 ./node_modules/<pluginKey>/manifest.json,
@@ -190,9 +190,9 @@ JSON 输出
190
190
  await (0, index_1.handlePluginList)(opts);
191
191
  });
192
192
  pluginCmd
193
- .command("list-packages")
194
- .description("列出 package.json actionPlugins 里已声明的插件包")
195
- .addHelpText("after", `
193
+ .command('list-packages')
194
+ .description('列出 package.json actionPlugins 里已声明的插件包')
195
+ .addHelpText('after', `
196
196
  行为
197
197
  - 读取 ./package.json 的 actionPlugins 字段
198
198
  - 只看声明,不校验 ./node_modules 下是否实际存在
@@ -16,10 +16,10 @@ const args_1 = require("../../utils/args");
16
16
  Object.defineProperty(exports, "failArgs", { enumerable: true, get: function () { return args_1.failArgs; } });
17
17
  /** --app-id option,需要应用上下文的命令自行 .addOption(appIdOption()) */
18
18
  function appIdOption() {
19
- return new commander_1.Option("--app-id <id>", "指定目标应用").env("MIAODA_APP_ID");
19
+ return new commander_1.Option('--app-id <id>', '指定目标应用').env('MIAODA_APP_ID');
20
20
  }
21
21
  function branchOption() {
22
- return new commander_1.Option("--branch <branch>", "分支(优先级:--branch > 当前仓库 HEAD 分支;非 git 目录回退应用默认分支)").env("LOCAL_MOCK_MIAODA_DEPLOY_BRANCH");
22
+ return new commander_1.Option('--branch <branch>', '分支(优先级:--branch > 当前仓库 HEAD 分支;非 git 目录回退应用默认分支)').env('LOCAL_MOCK_MIAODA_DEPLOY_BRANCH');
23
23
  }
24
24
  /**
25
25
  * soft-required: Commander 类型上 optional,runtime 校验必填。
@@ -36,8 +36,8 @@ function softRequiredOption(name, desc) {
36
36
  function resolveAppId(opts) {
37
37
  const id = opts.appId ?? process.env.MIAODA_APP_ID ?? process.env.app_id;
38
38
  if (!id) {
39
- throw new error_1.AppError("APP_ID_MISSING", "未指定应用", {
40
- next_actions: ["设置 export MIAODA_APP_ID=<id>"],
39
+ throw new error_1.AppError('APP_ID_MISSING', '未指定应用', {
40
+ next_actions: ['设置 export MIAODA_APP_ID=<id>'],
41
41
  });
42
42
  }
43
43
  return id;
@@ -53,7 +53,7 @@ function withHelp(cmd, handler) {
53
53
  await handler(...args);
54
54
  }
55
55
  catch (err) {
56
- if (err instanceof error_1.AppError && err.code === "ARGS_INVALID") {
56
+ if (err instanceof error_1.AppError && err.code === 'ARGS_INVALID') {
57
57
  process.stderr.write(`Error: ${err.message}\n`);
58
58
  cmd.outputHelp();
59
59
  process.exitCode = 2;
@@ -81,7 +81,7 @@ function caseInsensitiveChoice(canonical) {
81
81
  return (raw) => {
82
82
  const hit = map.get(raw.toLowerCase());
83
83
  if (hit === undefined) {
84
- throw new commander_1.InvalidArgumentError(`Allowed choices are ${canonical.join(", ")} (case-insensitive).`);
84
+ throw new commander_1.InvalidArgumentError(`Allowed choices are ${canonical.join(', ')} (case-insensitive).`);
85
85
  }
86
86
  return hit;
87
87
  };
@@ -98,8 +98,8 @@ function validateTimeOptions(opts, ...names) {
98
98
  const value = opts[name];
99
99
  if (value === undefined)
100
100
  continue;
101
- if (typeof value !== "string") {
102
- (0, args_1.failArgs)(`--${name.replace(/([A-Z])/g, "-$1").toLowerCase()} 必须是时间字符串`);
101
+ if (typeof value !== 'string') {
102
+ (0, args_1.failArgs)(`--${name.replace(/([A-Z])/g, '-$1').toLowerCase()} 必须是时间字符串`);
103
103
  }
104
104
  (0, time_1.parseTimeToMs)(value);
105
105
  }
@@ -118,8 +118,8 @@ function validateTimeOptions(opts, ...names) {
118
118
  */
119
119
  function rejectCliOverride(cmd, ...optNames) {
120
120
  for (const name of optNames) {
121
- if (cmd.getOptionValueSource(name) === "cli") {
122
- const flag = "--" + name.replace(/([A-Z])/g, "-$1").toLowerCase();
121
+ if (cmd.getOptionValueSource(name) === 'cli') {
122
+ const flag = '--' + name.replace(/([A-Z])/g, '-$1').toLowerCase();
123
123
  (0, args_1.failArgs)(`${flag} 由沙箱/本地配置注入,不允许显式传递`);
124
124
  }
125
125
  }
@@ -41,7 +41,7 @@ const index_1 = require("../../../api/app/index");
41
41
  /** miaoda app update [--app-id <id>] [--name <n>] [--description <d>] */
42
42
  async function handleAppUpdate(opts) {
43
43
  if (opts.name === undefined && opts.description === undefined) {
44
- (0, args_1.failArgs)("至少需要 --name 或 --description 中的一个");
44
+ (0, args_1.failArgs)('至少需要 --name 或 --description 中的一个');
45
45
  }
46
46
  const appID = opts.appId;
47
47
  await api.app.updateAppMeta({
@@ -53,7 +53,7 @@ async function handleAppUpdate(opts) {
53
53
  const resp = await api.app.getAppInfo(appID);
54
54
  const meta = resp.appInfo?.appMeta ?? {};
55
55
  if (!(0, output_1.isJsonMode)()) {
56
- process.stdout.write("✓ App updated successfully\n");
56
+ process.stdout.write('✓ App updated successfully\n');
57
57
  }
58
58
  (0, output_1.emit)({ data: meta }, index_1.appMetaSchema);
59
59
  }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ // changelog / audit 共用:把后端透传的 operator 字符串还原成 {id, name}。
3
+ //
4
+ // 后端约定:Operator 字段值是 `{"id":"<user_id>","name":"<resolved_name>"}` JSON
5
+ // 字符串(dataloom inner_service.encodeOperator 生成),用同一字段同时承载机器可
6
+ // 识别的 user_id 与人类可读 name。
7
+ //
8
+ // 选择"字符串内嵌 JSON"而不是 IDL struct,是为了避免 dataloom_inner.thrift +
9
+ // kitex_gen 跨仓库改造;CLI 端 JSON.parse 拆开即可分场景渲染:
10
+ // - --json 模式:返 {id, name} 对象(agent / 下游能区分同名用户)
11
+ // - pretty 模式:只取 name(兼容 PRD 原始 string 形态)
12
+ //
13
+ // 历史数据 / 旧版后端没接这层时,operator 仍是纯字符串。该函数兼容:
14
+ // - 解析失败 → 当作 {id: raw, name: raw}
15
+ // - 解析成功但缺字段 → 用现有字段兜底另一个
16
+ // 解析失败默认不报错,保留 raw 作为兜底显示文本。
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.parseOperator = parseOperator;
19
+ function parseOperator(raw) {
20
+ if (raw === undefined || raw === null || raw === '') {
21
+ return { id: '', name: '' };
22
+ }
23
+ if (!raw.startsWith('{')) {
24
+ return { id: raw, name: raw };
25
+ }
26
+ try {
27
+ const obj = JSON.parse(raw);
28
+ const id = typeof obj.id === 'string' ? obj.id : '';
29
+ const name = typeof obj.name === 'string' && obj.name !== '' ? obj.name : id;
30
+ return { id, name };
31
+ }
32
+ catch {
33
+ return { id: raw, name: raw };
34
+ }
35
+ }
@@ -38,19 +38,20 @@ exports.handleDbAuditEnable = handleDbAuditEnable;
38
38
  exports.handleDbAuditDisable = handleDbAuditDisable;
39
39
  exports.handleDbAuditList = handleDbAuditList;
40
40
  const api = __importStar(require("../../../api/index"));
41
- const index_1 = require("../../../api/file/index");
42
41
  const shared_1 = require("../../../cli/commands/shared");
43
42
  const colors_1 = require("../../../utils/colors");
44
43
  const error_1 = require("../../../utils/error");
45
44
  const output_1 = require("../../../utils/output");
46
45
  const render_1 = require("../../../utils/render");
47
- const VALID_RETENTION = new Set(["7d", "30d", "180d", "360d", "forever"]);
46
+ const time_1 = require("../../../utils/time");
47
+ const _operator_1 = require("../../../cli/handlers/db/_operator");
48
+ const VALID_RETENTION = new Set(['7d', '30d', '180d', '360d', 'forever']);
48
49
  async function handleDbAuditStatus(table, opts) {
49
50
  const appId = (0, shared_1.resolveAppId)(opts);
50
51
  const items = await api.db.getAuditStatus({ appId, table, dbBranch: opts.env });
51
52
  const rows = items.map(toAuditStatus);
52
53
  // 单表查询但后端没记录 → 占位 enabled=false
53
- if (table !== undefined && table !== "" && rows.length === 0) {
54
+ if (table !== undefined && table !== '' && rows.length === 0) {
54
55
  rows.push({ table, enabled: false, enabled_at: null, retention: null });
55
56
  }
56
57
  // PRD JSON:单表返 object,多表返 array
@@ -64,7 +65,7 @@ async function handleDbAuditStatus(table, opts) {
64
65
  return;
65
66
  }
66
67
  if (rows.length === 0) {
67
- (0, output_1.emit)("No audit configuration found.");
68
+ (0, output_1.emit)('No audit configuration found.');
68
69
  return;
69
70
  }
70
71
  const tty = (0, render_1.isStdoutTty)();
@@ -72,20 +73,20 @@ async function handleDbAuditStatus(table, opts) {
72
73
  if (table !== undefined && rows.length === 1) {
73
74
  const it = rows[0];
74
75
  (0, output_1.emit)((0, render_1.renderKeyValue)([
75
- ["Table", it.table],
76
- ["Enabled", boolToYesNo(it.enabled)],
77
- ["Enabled at", it.enabled_at ? (0, render_1.formatTime)(it.enabled_at, tty) : "—"],
78
- ["Retention", it.retention ?? "—"],
76
+ ['Table', it.table],
77
+ ['Enabled', boolToYesNo(it.enabled)],
78
+ ['Enabled at', it.enabled_at ? (0, render_1.formatTime)(it.enabled_at, tty) : '—'],
79
+ ['Retention', it.retention ?? '—'],
79
80
  ], tty));
80
81
  return;
81
82
  }
82
83
  // 列表 → table 形态
83
- const headers = ["table", "enabled", "enabled_at", "retention"];
84
+ const headers = ['table', 'enabled', 'enabled_at', 'retention'];
84
85
  const out = rows.map((it) => [
85
86
  it.table,
86
87
  boolToYesNo(it.enabled),
87
- it.enabled_at ? (0, render_1.formatTime)(it.enabled_at, tty) : "—",
88
- it.retention ?? "—",
88
+ it.enabled_at ? (0, render_1.formatTime)(it.enabled_at, tty) : '—',
89
+ it.retention ?? '—',
89
90
  ]);
90
91
  (0, output_1.emit)(tty ? (0, render_1.renderAlignedTable)(headers, out) : (0, render_1.renderTsv)(headers, out));
91
92
  }
@@ -99,16 +100,16 @@ function toAuditStatus(s) {
99
100
  }
100
101
  async function handleDbAuditEnable(table, opts) {
101
102
  if (!table) {
102
- throw new error_1.AppError("ARGS_INVALID", "table name is required", {
103
+ throw new error_1.AppError('ARGS_INVALID', 'table name is required', {
103
104
  next_actions: [
104
- "Usage: miaoda db audit enable <table> [--retention 7d|30d|180d|360d|forever]",
105
+ 'Usage: miaoda db audit enable <table> [--retention 7d|30d|180d|360d|forever]',
105
106
  ],
106
107
  });
107
108
  }
108
- const retention = opts.retention ?? "7d";
109
+ const retention = opts.retention ?? '7d';
109
110
  if (!VALID_RETENTION.has(retention)) {
110
- throw new error_1.AppError("INVALID_RETENTION", `Invalid retention '${retention}'`, {
111
- next_actions: ["Allowed values: 7d, 30d, 180d, 360d, forever."],
111
+ throw new error_1.AppError('INVALID_RETENTION', `Invalid retention '${retention}'`, {
112
+ next_actions: ['Allowed values: 7d, 30d, 180d, 360d, forever.'],
112
113
  });
113
114
  }
114
115
  const appId = (0, shared_1.resolveAppId)(opts);
@@ -124,7 +125,7 @@ async function handleDbAuditEnable(table, opts) {
124
125
  }
125
126
  catch (err) {
126
127
  // PRD: 重复 enable 报错时附带 hint,引导用户去 status 看 retention 或换值更新
127
- if (err instanceof error_1.AppError && err.code === "DB_API_k_dl_1300030") {
128
+ if (err instanceof error_1.AppError && err.code === 'DB_API_k_dl_1300030') {
128
129
  throw new error_1.AppError(err.code, err.message, {
129
130
  next_actions: [
130
131
  `Use \`miaoda db audit status ${table}\` to check current retention, or run this command with a different --retention to update.`,
@@ -143,15 +144,15 @@ async function handleDbAuditEnable(table, opts) {
143
144
  return;
144
145
  }
145
146
  const tty = (0, render_1.isStdoutTty)();
146
- const prefix = tty ? "✓" : "OK";
147
147
  // c.highlight 内部按 TTY/NO_COLOR/FORCE_COLOR 自动决定是否染色,无需再判 tty
148
148
  const tableLabel = colors_1.c.highlight(`'${status.table}'`);
149
- (0, output_1.emit)(`${prefix} Audit enabled for table ${tableLabel} (retention: ${status.retention ?? retention})`);
149
+ const body = `Audit enabled for table ${tableLabel} (retention: ${status.retention ?? retention})`;
150
+ (0, output_1.emit)(tty ? colors_1.c.success(`✓ ${body}`) : `OK ${body}`);
150
151
  }
151
152
  async function handleDbAuditDisable(table, opts) {
152
153
  if (!table) {
153
- throw new error_1.AppError("ARGS_INVALID", "table name is required", {
154
- next_actions: ["Usage: miaoda db audit disable <table>"],
154
+ throw new error_1.AppError('ARGS_INVALID', 'table name is required', {
155
+ next_actions: ['Usage: miaoda db audit disable <table>'],
155
156
  });
156
157
  }
157
158
  const appId = (0, shared_1.resolveAppId)(opts);
@@ -166,9 +167,9 @@ async function handleDbAuditDisable(table, opts) {
166
167
  }
167
168
  catch (err) {
168
169
  // PRD: 重复 disable / 未启用就 disable 报错时附带 hint,引导用户去看哪些表已开启
169
- if (err instanceof error_1.AppError && err.code === "DB_API_k_dl_1300031") {
170
+ if (err instanceof error_1.AppError && err.code === 'DB_API_k_dl_1300031') {
170
171
  throw new error_1.AppError(err.code, err.message, {
171
- next_actions: ["Use `miaoda db audit status` to see which tables have audit enabled."],
172
+ next_actions: ['Use `miaoda db audit status` to see which tables have audit enabled.'],
172
173
  });
173
174
  }
174
175
  throw err;
@@ -181,14 +182,14 @@ async function handleDbAuditDisable(table, opts) {
181
182
  return;
182
183
  }
183
184
  const tty = (0, render_1.isStdoutTty)();
184
- const prefix = tty ? "✓" : "OK";
185
- (0, output_1.emit)(`${prefix} Audit disabled for table ${colors_1.c.highlight(`'${status.table}'`)}`);
185
+ const body = `Audit disabled for table ${colors_1.c.highlight(`'${status.table}'`)}`;
186
+ (0, output_1.emit)(tty ? colors_1.c.success(`✓ ${body}`) : `OK ${body}`);
186
187
  }
187
188
  async function handleDbAuditList(tables, opts) {
188
189
  if (tables.length === 0) {
189
- throw new error_1.AppError("ARGS_INVALID", "at least one table is required", {
190
+ throw new error_1.AppError('ARGS_INVALID', 'at least one table is required', {
190
191
  next_actions: [
191
- "Usage: miaoda db audit list <table> [<table>...] [--since ...] [--until ...]",
192
+ 'Usage: miaoda db audit list <table> [<table>...] [--since ...] [--until ...]',
192
193
  ],
193
194
  });
194
195
  }
@@ -196,27 +197,34 @@ async function handleDbAuditList(tables, opts) {
196
197
  const limit = opts.limit ?? 20;
197
198
  // 时间字段归一化为 ISO 8601 UTC(服务端按 event_time 字段比较)。cursor 由
198
199
  // 后端管理(本质也是 ISO 时间),CLI 不再混用 cursor/since。
199
- const since = normalizeTime(opts.since, "--since");
200
- const until = normalizeTime(opts.until, "--until");
201
- const result = await api.db.listAuditLog({
202
- appId,
203
- tables,
204
- since,
205
- until,
206
- limit,
207
- cursor: opts.cursor,
208
- dbBranch: opts.env,
209
- });
200
+ const since = normalizeTime(opts.since, '--since');
201
+ const until = normalizeTime(opts.until, '--until');
202
+ let result;
203
+ try {
204
+ result = await api.db.listAuditLog({
205
+ appId,
206
+ tables,
207
+ since,
208
+ until,
209
+ limit,
210
+ cursor: opts.cursor,
211
+ dbBranch: opts.env,
212
+ });
213
+ }
214
+ catch (err) {
215
+ throw decorateAuditListError(err, tables);
216
+ }
210
217
  const visible = result.items;
211
218
  const skipped = result.skipped;
212
219
  // PRD JSON:data 是数组,元素是事件对象(snake_case),分页信封 next_cursor / has_more
220
+ // operator 后端用 JSON 字符串内嵌 {id, name},--json 输出还原成对象供下游消费
213
221
  if ((0, output_1.isJsonMode)()) {
214
222
  const items = visible.map((it) => ({
215
223
  event_id: it.eventId,
216
224
  event_time: it.eventTime,
217
225
  target_table: it.targetTable,
218
226
  type: it.type,
219
- operator: it.operator,
227
+ operator: (0, _operator_1.parseOperator)(it.operator),
220
228
  summary: it.summary,
221
229
  // before/after 服务端是 JSON 字符串,反序列化回结构化对象供下游消费
222
230
  ...(it.before !== undefined ? { before: safeParseJson(it.before) } : {}),
@@ -224,16 +232,16 @@ async function handleDbAuditList(tables, opts) {
224
232
  }));
225
233
  (0, output_1.emitPaged)(items, result.nextCursor, result.hasMore);
226
234
  if (skipped.length > 0) {
227
- process.stderr.write(`(${String(skipped.length)} table(s) skipped: ${skipped.join(", ")})\n`);
235
+ process.stderr.write(formatSkippedHint(skipped, tables.length) + '\n');
228
236
  }
229
237
  if (visible.length === 0)
230
238
  process.exitCode = 1;
231
239
  return;
232
240
  }
233
241
  if (visible.length === 0) {
234
- (0, output_1.emit)("No audit log entries found.");
242
+ (0, output_1.emit)('No audit log entries found.');
235
243
  if (skipped.length > 0) {
236
- process.stderr.write(`(${String(skipped.length)} table(s) skipped: ${skipped.join(", ")})\n`);
244
+ process.stderr.write(formatSkippedHint(skipped, tables.length) + '\n');
237
245
  }
238
246
  process.exitCode = 1;
239
247
  return;
@@ -242,32 +250,75 @@ async function handleDbAuditList(tables, opts) {
242
250
  // PRD:多表渲染时第一列是 target_table,单表时去掉这一列
243
251
  const isMultiTable = tables.length > 1;
244
252
  const headers = isMultiTable
245
- ? ["target_table", "event_time", "type", "event_id", "operator", "summary"]
246
- : ["event_time", "type", "event_id", "operator", "summary"];
253
+ ? ['target_table', 'event_time', 'type', 'event_id', 'operator', 'summary']
254
+ : ['event_time', 'type', 'event_id', 'operator', 'summary'];
247
255
  const rows = visible.map((it) => {
248
256
  const eventTime = (0, render_1.formatTime)(it.eventTime, tty);
249
257
  // event_id 完整透传——PRD 截图里的 "..." 只是文档省略写法,不是 CLI 行为
250
- const cells = [eventTime, it.type, it.eventId, it.operator || "—", it.summary];
258
+ // operator pretty 只展示 name;--json 上面已经走 parseOperator 输出 {id, name}
259
+ const cells = [
260
+ eventTime,
261
+ it.type,
262
+ it.eventId,
263
+ (0, _operator_1.parseOperator)(it.operator).name || '—',
264
+ it.summary,
265
+ ];
251
266
  return isMultiTable ? [it.targetTable, ...cells] : cells;
252
267
  });
253
268
  (0, output_1.emit)(tty ? (0, render_1.renderAlignedTable)(headers, rows) : (0, render_1.renderTsv)(headers, rows));
254
269
  if (skipped.length > 0) {
255
- process.stderr.write(`(${String(skipped.length)} table(s) skipped: ${skipped.join(", ")})\n`);
270
+ process.stderr.write(formatSkippedHint(skipped, tables.length) + '\n');
256
271
  }
257
272
  if (result.hasMore && result.nextCursor) {
258
273
  process.stderr.write(`(more results; use --cursor '${result.nextCursor}')\n`);
259
274
  }
260
275
  }
261
276
  // ── helpers ──
277
+ /**
278
+ * 把用户传入的 since/until 归一成 ISO 8601 UTC 字符串;空串返 undefined。
279
+ * 支持格式见 utils/time.ts::TIMESTAMP_HELP(相对时间 / 日期 / 本地 datetime / ISO 8601)。
280
+ */
262
281
  function normalizeTime(input, flagName) {
263
- if (input === undefined || input === "")
282
+ if (input === undefined || input === '')
264
283
  return undefined;
265
- // ISO 8601 直接透传,避免 parseTimeFilterMs 在严格 ISO 上重做一次损精度
266
- if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/.test(input)) {
267
- return new Date(input).toISOString();
284
+ try {
285
+ return new Date((0, time_1.parseTimeToMs)(input)).toISOString();
286
+ }
287
+ catch (err) {
288
+ if (err instanceof error_1.AppError) {
289
+ throw new error_1.AppError(err.code, `${flagName}: ${err.message}`, {
290
+ next_actions: err.next_actions,
291
+ });
292
+ }
293
+ throw err;
294
+ }
295
+ }
296
+ // PRD 41-48 行格式:`— Skipped 1 of 3 tables: orders (audit not enabled)`
297
+ // 服务端约定 skipped 列表 = audit 未启用的表(表不存在直接 raise k_dl_000005),
298
+ // 所以原因固定为 "audit not enabled",无需带每项 reason。
299
+ function formatSkippedHint(skipped, totalRequested) {
300
+ const items = skipped.map((t) => `${t} (audit not enabled)`).join(', ');
301
+ return `— Skipped ${String(skipped.length)} of ${String(totalRequested)} tables: ${items}`;
302
+ }
303
+ // audit list 后端两个新错误码加 hint:
304
+ // - k_dl_1300040 单表 audit 未启用 → 指引 enable
305
+ // - k_dl_1300041 多表全部未启用 → 指引 status
306
+ // 其他错误(表不存在 k_dl_000005 等)保留 mapDbHttpError 已有文案,不再二次包装。
307
+ function decorateAuditListError(err, tables) {
308
+ if (!(err instanceof error_1.AppError))
309
+ return err;
310
+ if (err.code === 'DB_API_k_dl_1300040') {
311
+ const t = tables[0] ?? '<table>';
312
+ return new error_1.AppError(err.code, err.message, {
313
+ next_actions: [`Enable with: miaoda db audit enable ${t}`],
314
+ });
315
+ }
316
+ if (err.code === 'DB_API_k_dl_1300041') {
317
+ return new error_1.AppError(err.code, err.message, {
318
+ next_actions: ['Check audit status with: miaoda db audit status'],
319
+ });
268
320
  }
269
- const ms = (0, index_1.parseTimeFilterMs)(input, flagName);
270
- return new Date(ms).toISOString();
321
+ return err;
271
322
  }
272
323
  // 服务端 before/after 是 JSON 字符串透传,CLI JSON 输出再反序列化回对象,
273
324
  // 给下游 jq 等工具消费。失败时透传原始字符串避免数据丢失。
@@ -281,5 +332,5 @@ function safeParseJson(s) {
281
332
  }
282
333
  // PRD 输出 enabled 列用 yes/no 而非 true/false
283
334
  function boolToYesNo(b) {
284
- return b ? "yes" : "no";
335
+ return b ? 'yes' : 'no';
285
336
  }
@@ -35,32 +35,46 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.handleDbChangelog = handleDbChangelog;
37
37
  const api = __importStar(require("../../../api/index"));
38
- const index_1 = require("../../../api/file/index");
39
38
  const shared_1 = require("../../../cli/commands/shared");
39
+ const error_1 = require("../../../utils/error");
40
40
  const output_1 = require("../../../utils/output");
41
41
  const render_1 = require("../../../utils/render");
42
+ const time_1 = require("../../../utils/time");
43
+ const _operator_1 = require("../../../cli/handlers/db/_operator");
42
44
  function toRow(it) {
43
45
  return {
44
46
  change_id: it.changeId,
45
47
  changed_at: it.changedAt,
46
- operator: it.operator,
48
+ operator: (0, _operator_1.parseOperator)(it.operator),
47
49
  target_table: it.targetTable,
48
50
  change_type: it.changeType,
49
51
  summary: it.summary,
50
52
  statement: it.statement,
51
53
  };
52
54
  }
53
- /** 把用户传入的 since/until 归一成 ISO 8601 UTC 字符串;空串返 undefined。 */
55
+ /**
56
+ * 把用户传入的 since/until 归一成 ISO 8601 UTC 字符串;空串返 undefined。
57
+ * 支持格式见 utils/time.ts::TIMESTAMP_HELP(相对时间 / 日期 / 本地 datetime / ISO 8601)。
58
+ */
54
59
  function normalizeTime(input, flagName) {
55
- if (input === undefined || input === "")
60
+ if (input === undefined || input === '')
56
61
  return undefined;
57
- const ms = (0, index_1.parseTimeFilterMs)(input, flagName);
58
- return new Date(ms).toISOString();
62
+ try {
63
+ return new Date((0, time_1.parseTimeToMs)(input)).toISOString();
64
+ }
65
+ catch (err) {
66
+ if (err instanceof error_1.AppError) {
67
+ throw new error_1.AppError(err.code, `${flagName}: ${err.message}`, {
68
+ next_actions: err.next_actions,
69
+ });
70
+ }
71
+ throw err;
72
+ }
59
73
  }
60
74
  async function handleDbChangelog(opts) {
61
75
  const appId = (0, shared_1.resolveAppId)(opts);
62
- const since = normalizeTime(opts.since, "--since");
63
- const until = normalizeTime(opts.until, "--until");
76
+ const since = normalizeTime(opts.since, '--since');
77
+ const until = normalizeTime(opts.until, '--until');
64
78
  const allItems = [];
65
79
  let cursor = opts.cursor;
66
80
  let lastCursor = null;
@@ -96,19 +110,20 @@ async function handleDbChangelog(opts) {
96
110
  return;
97
111
  }
98
112
  if (allItems.length === 0) {
99
- (0, output_1.emit)("No DDL changes found.");
113
+ (0, output_1.emit)('No DDL changes found.');
100
114
  return;
101
115
  }
102
116
  const tty = (0, render_1.isStdoutTty)();
103
117
  // PRD: change_id / changed_at / operator / target_table / change_type / summary
104
- const headers = ["change_id", "changed_at", "operator", "target_table", "change_type", "summary"];
118
+ const headers = ['change_id', 'changed_at', 'operator', 'target_table', 'change_type', 'summary'];
119
+ // pretty 渲染只展示 operator.name(兼容 PRD 原 string 形态);--json 走 toRow 输出完整对象
105
120
  const rows = allItems.map((it) => [
106
121
  it.changeId,
107
122
  (0, render_1.formatTime)(it.changedAt, tty),
108
- it.operator || "—",
109
- it.targetTable || "—",
123
+ (0, _operator_1.parseOperator)(it.operator).name || '—',
124
+ it.targetTable || '—',
110
125
  it.changeType,
111
- it.summary || "—",
126
+ it.summary || '—',
112
127
  ]);
113
128
  (0, output_1.emit)(tty ? (0, render_1.renderAlignedTable)(headers, rows) : (0, render_1.renderTsv)(headers, rows));
114
129
  if (!opts.all && lastHasMore && lastCursor) {