@lark-apaas/miaoda-cli 0.1.1 → 0.1.2-alpha.08ca9fb

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 (68) hide show
  1. package/README.md +8 -7
  2. package/dist/api/app/api.js +25 -0
  3. package/dist/api/app/index.js +15 -0
  4. package/dist/api/app/schemas.js +79 -0
  5. package/dist/api/app/types.js +58 -0
  6. package/dist/api/db/api.js +83 -6
  7. package/dist/api/db/client.js +40 -29
  8. package/dist/api/db/parsers.js +33 -20
  9. package/dist/api/db/sql-keywords.js +123 -0
  10. package/dist/api/deploy/api.js +60 -0
  11. package/dist/api/deploy/index.js +16 -0
  12. package/dist/api/deploy/schemas.js +105 -0
  13. package/dist/api/deploy/types.js +22 -0
  14. package/dist/api/file/api.js +78 -24
  15. package/dist/api/file/client.js +1 -5
  16. package/dist/api/file/parsers.js +1 -5
  17. package/dist/api/index.js +7 -1
  18. package/dist/api/observability/api.js +52 -0
  19. package/dist/api/observability/index.js +16 -0
  20. package/dist/api/observability/schemas.js +60 -0
  21. package/dist/api/observability/types.js +27 -0
  22. package/dist/api/plugin/api.js +8 -3
  23. package/dist/cli/commands/app/index.js +62 -0
  24. package/dist/cli/commands/db/index.js +1 -0
  25. package/dist/cli/commands/deploy/index.js +148 -0
  26. package/dist/cli/commands/index.js +10 -6
  27. package/dist/cli/commands/observability/index.js +240 -0
  28. package/dist/cli/commands/plugin/index.js +18 -6
  29. package/dist/cli/commands/shared.js +82 -6
  30. package/dist/cli/handlers/app/get.js +48 -0
  31. package/dist/cli/handlers/app/index.js +7 -0
  32. package/dist/cli/handlers/app/update.js +59 -0
  33. package/dist/cli/handlers/db/data.js +22 -2
  34. package/dist/cli/handlers/db/schema.js +22 -8
  35. package/dist/cli/handlers/db/sql.js +304 -16
  36. package/dist/cli/handlers/deploy/deploy.js +84 -0
  37. package/dist/cli/handlers/deploy/error-log.js +60 -0
  38. package/dist/cli/handlers/deploy/format.js +39 -0
  39. package/dist/cli/handlers/deploy/get.js +71 -0
  40. package/dist/cli/handlers/deploy/helpers.js +41 -0
  41. package/dist/cli/handlers/deploy/history.js +71 -0
  42. package/dist/cli/handlers/deploy/index.js +14 -0
  43. package/dist/cli/handlers/deploy/polling.js +162 -0
  44. package/dist/cli/handlers/file/cp.js +39 -17
  45. package/dist/cli/handlers/file/ls.js +1 -3
  46. package/dist/cli/handlers/file/rm.js +4 -3
  47. package/dist/cli/handlers/observability/analytics.js +212 -0
  48. package/dist/cli/handlers/observability/helpers.js +66 -0
  49. package/dist/cli/handlers/observability/index.js +12 -0
  50. package/dist/cli/handlers/observability/log.js +95 -0
  51. package/dist/cli/handlers/observability/metric.js +208 -0
  52. package/dist/cli/handlers/observability/trace.js +102 -0
  53. package/dist/cli/handlers/plugin/plugin-local.js +23 -9
  54. package/dist/cli/handlers/plugin/plugin.js +21 -7
  55. package/dist/cli/help.js +5 -2
  56. package/dist/cli/version.js +15 -0
  57. package/dist/main.js +27 -7
  58. package/dist/utils/colors.js +98 -0
  59. package/dist/utils/devops-error.js +28 -0
  60. package/dist/utils/error.js +11 -0
  61. package/dist/utils/fuzzy-match.js +91 -0
  62. package/dist/utils/git.js +29 -0
  63. package/dist/utils/http.js +118 -0
  64. package/dist/utils/index.js +13 -1
  65. package/dist/utils/output.js +397 -12
  66. package/dist/utils/render.js +61 -41
  67. package/dist/utils/time.js +203 -0
  68. package/package.json +16 -6
@@ -179,6 +179,7 @@ Examples:
179
179
  .option("--format <fmt>", "导出格式 csv / json / sql,默认 csv(sql 输出 INSERT 语句,可用 db sql < file.sql 回放)")
180
180
  .option("-f, --file <path>", "输出文件路径,默认 <表名>.<格式>")
181
181
  .option("--limit <n>", "最多导出行数(不超过 5000)")
182
+ .option("--force", "输出文件已存在时覆盖(默认报错)")
182
183
  .action(async function (table) {
183
184
  await (0, index_1.handleDbDataExport)(table, this.optsWithGlobals());
184
185
  })
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerDeployCommands = registerDeployCommands;
4
+ const commander_1 = require("commander");
5
+ const shared_1 = require("../../../cli/commands/shared");
6
+ const index_1 = require("../../../cli/handlers/deploy/index");
7
+ const COMMON_TIME_HELP = `
8
+ 时间格式:
9
+ - 相对时间:30m(30 分钟前)、1h、2d、1w
10
+ - 日期:2026-04-01(本地时区当日 00:00:00)
11
+ - 本地日期+时间:2026-04-01T10:00:00(按本地时区,T 分隔)
12
+ - 带时区 ISO:2026-04-01T10:00:00Z(UTC)或 2026-04-01T10:00:00+08:00(指定偏移)
13
+ 备注:
14
+ 1) 不带时区的形式与 pretty 输出闭环(同机器复制粘贴稳定);跨机器请带显式时区。
15
+ 2) 必须用 T 分隔日期与时间,禁止空格——shell 会把不带引号的 'YYYY-MM-DD HH:mm:ss' 拆成两个参数。
16
+ `;
17
+ function registerDeployCommands(program) {
18
+ // PRD:`miaoda deploy` 自身即为触发发布;get / history / error-log 是子命令
19
+ const deployCmd = program
20
+ .command("deploy")
21
+ .description("触发发布;支持 --wait 阻塞到终态。子命令:get / history / error-log")
22
+ .addOption((0, shared_1.appIdOption)().hideHelp())
23
+ .addOption((0, shared_1.branchOption)().hideHelp())
24
+ .option("--wait", "阻塞直到流水线终态", false)
25
+ .option("--timeout <sec>", "--wait 最长等待秒数(默认 300)", parseTimeout, 300)
26
+ .addHelpText("after", `
27
+ 部署前置检查(Agent 必须执行)
28
+ miaoda deploy 跑的是当前分支的远端 HEAD——本地未 commit / 未 push 的代码不会进发布产物。
29
+ 调用前先 \`git status\` + \`git rev-list --count @{u}..HEAD\` 确认;有未提交 / 未推送时:
30
+ - 是本次任务的产物 → 先 commit + push 再 deploy
31
+ - 不能确定意图 → 用 AskUser 跟用户确认(不要默默继续)
32
+
33
+ JSON 输出
34
+ 不带 --wait:{"data": {"pipelineTaskID": "..."}}(pipelineTaskID 即 deploy-id)
35
+ 带 --wait:data 额外包含 detail(pipeline 终态)
36
+ detail/status 字段为可读字符串;对应 *_code 字段保留 BAM 原始数字枚举。
37
+
38
+ 示例
39
+ $ miaoda deploy
40
+ $ miaoda deploy --wait --timeout 600
41
+ $ miaoda deploy get 12345
42
+ $ miaoda deploy history --status failed
43
+ `);
44
+ deployCmd.action((0, shared_1.withHelp)(deployCmd, async (rawOpts) => {
45
+ (0, shared_1.rejectCliOverride)(deployCmd, "appId", "branch");
46
+ await (0, index_1.handleDeploy)({
47
+ appId: rawOpts.appId,
48
+ branch: rawOpts.branch,
49
+ wait: rawOpts.wait,
50
+ timeout: rawOpts.timeout,
51
+ });
52
+ }));
53
+ registerDeployGet(deployCmd);
54
+ registerDeployHistory(deployCmd);
55
+ registerDeployErrorLog(deployCmd);
56
+ }
57
+ function registerDeployGet(parent) {
58
+ const cmd = parent
59
+ .command("get")
60
+ .description("查看指定发布单的详情")
61
+ .argument("<deploy-id>", "发布单 ID")
62
+ .addOption((0, shared_1.appIdOption)().hideHelp())
63
+ .addHelpText("after", `
64
+ JSON 输出
65
+ {"data": {"ID": ..., "status": ..., "creator": "...", "createdAt": ..., "updatedAt": ..., ...}, "next_cursor": null, "has_more": false}
66
+ ID 即 deploy-id(== pipelineTaskID)
67
+ data.status 为可读字符串;data.status_code 为 BAM 原始数字枚举。
68
+
69
+ 示例
70
+ $ miaoda deploy get 12345
71
+ `);
72
+ cmd.action((0, shared_1.withHelp)(cmd, async (deployId, rawOpts) => {
73
+ (0, shared_1.rejectCliOverride)(cmd, "appId");
74
+ await (0, index_1.handleDeployGet)({
75
+ deployId,
76
+ appId: rawOpts.appId,
77
+ });
78
+ }));
79
+ }
80
+ function registerDeployHistory(parent) {
81
+ const cmd = parent
82
+ .command("history")
83
+ .description("查询发布历史(按时间倒序,分页)")
84
+ .addOption((0, shared_1.appIdOption)().hideHelp())
85
+ .addOption(new commander_1.Option("--status <status>", "状态过滤(pipeline 节点状态,大小写不敏感)")
86
+ .choices(["todo", "running", "success", "failed", "canceled", "hold_on"])
87
+ .argParser((0, shared_1.caseInsensitiveChoice)(["todo", "running", "success", "failed", "canceled", "hold_on"])))
88
+ .option("--since <time>", "起始时间")
89
+ .option("--until <time>", "截止时间")
90
+ .option("--limit <n>", "返回条数上限(1~100)", parseLimit, 50)
91
+ .option("--cursor <token>", "下一页游标")
92
+ .addHelpText("after", `${COMMON_TIME_HELP}
93
+ JSON 输出
94
+ {"data": [...], "next_cursor": "...", "has_more": true|false}
95
+ data[].status 为可读字符串;data[].status_code 为 BAM 原始数字枚举。
96
+
97
+ 示例
98
+ $ miaoda deploy history --status failed
99
+ $ miaoda deploy history --since 7d
100
+ `);
101
+ cmd.action((0, shared_1.withHelp)(cmd, async (rawOpts) => {
102
+ (0, shared_1.validateTimeOptions)(rawOpts, "since", "until");
103
+ (0, shared_1.rejectCliOverride)(cmd, "appId");
104
+ await (0, index_1.handleDeployHistory)({
105
+ appId: rawOpts.appId,
106
+ status: rawOpts.status,
107
+ since: rawOpts.since,
108
+ until: rawOpts.until,
109
+ limit: rawOpts.limit,
110
+ cursor: rawOpts.cursor,
111
+ });
112
+ }));
113
+ }
114
+ function registerDeployErrorLog(parent) {
115
+ const cmd = parent
116
+ .command("error-log")
117
+ .description("查询指定发布的错误日志")
118
+ .argument("<deploy-id>", "发布单 ID")
119
+ .addOption((0, shared_1.appIdOption)().hideHelp())
120
+ .addHelpText("after", `
121
+ JSON 输出
122
+ {"data": [{"jobID": ..., "componentName": ..., "errorMsg": ...}], "next_cursor": null, "has_more": false}
123
+
124
+ 示例
125
+ $ miaoda deploy error-log 12345 --json
126
+ `);
127
+ cmd.action((0, shared_1.withHelp)(cmd, async (deployId, rawOpts) => {
128
+ (0, shared_1.rejectCliOverride)(cmd, "appId");
129
+ await (0, index_1.handleDeployErrorLog)({
130
+ deployId,
131
+ appId: rawOpts.appId,
132
+ });
133
+ }));
134
+ }
135
+ function parseLimit(value) {
136
+ const n = Number(value);
137
+ if (!Number.isFinite(n)) {
138
+ throw new Error(`--limit 必须是数字,收到 '${value}'`);
139
+ }
140
+ return n;
141
+ }
142
+ function parseTimeout(value) {
143
+ const n = Number(value);
144
+ if (!Number.isFinite(n) || n <= 0) {
145
+ throw new Error(`--timeout 必须是正数,收到 '${value}'`);
146
+ }
147
+ return n;
148
+ }
@@ -1,11 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.registerCommands = registerCommands;
4
- const index_1 = require("../../cli/commands/plugin/index");
5
- const index_2 = require("../../cli/commands/file/index");
6
- const index_3 = require("../../cli/commands/db/index");
4
+ const index_1 = require("../../cli/commands/file/index");
5
+ const index_2 = require("../../cli/commands/db/index");
6
+ const index_3 = require("../../cli/commands/observability/index");
7
+ const index_4 = require("../../cli/commands/app/index");
8
+ const index_5 = require("../../cli/commands/deploy/index");
7
9
  function registerCommands(program) {
8
- (0, index_1.registerPluginCommands)(program);
9
- (0, index_2.registerFileCommands)(program);
10
- (0, index_3.registerDbCommands)(program);
10
+ (0, index_1.registerFileCommands)(program);
11
+ (0, index_2.registerDbCommands)(program);
12
+ (0, index_3.registerObservabilityCommands)(program);
13
+ (0, index_4.registerAppCommands)(program);
14
+ (0, index_5.registerDeployCommands)(program);
11
15
  }
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerObservabilityCommands = registerObservabilityCommands;
4
+ const commander_1 = require("commander");
5
+ const shared_1 = require("../../../cli/commands/shared");
6
+ const index_1 = require("../../../cli/handlers/observability/index");
7
+ const COMMON_TIME_HELP = `
8
+ 时间格式:
9
+ - 相对时间:30m(30 分钟前)、1h、2d、1w
10
+ - 日期:2026-04-01(本地时区当日 00:00:00)
11
+ - 本地日期+时间:2026-04-01T10:00:00(按本地时区,T 分隔)
12
+ - 带时区 ISO:2026-04-01T10:00:00Z(UTC)或 2026-04-01T10:00:00+08:00(指定偏移)
13
+ 备注:
14
+ 1) 不带时区的形式与 pretty 输出闭环(同机器复制粘贴稳定);跨机器请带显式时区。
15
+ 2) 必须用 T 分隔日期与时间,禁止空格——shell 会把不带引号的 'YYYY-MM-DD HH:mm:ss' 拆成两个参数。
16
+ `;
17
+ function registerObservabilityCommands(program) {
18
+ const obCmd = program
19
+ .command("observability")
20
+ .description("可观测性:查询线上日志、链路、监控指标、运营指标");
21
+ obCmd.action(() => {
22
+ obCmd.outputHelp();
23
+ });
24
+ obCmd.addHelpText("after", `
25
+ 作用范围
26
+ 仅供 Agent 在妙搭沙箱内调用,查询当前应用的线上观测数据。所有命令为只读。
27
+ 应用上下文:--app-id <id> 或环境变量 MIAODA_APP_ID。
28
+
29
+ 应用环境
30
+ 目前只支持线上环境。
31
+ `);
32
+ registerLog(obCmd);
33
+ registerTrace(obCmd);
34
+ registerMetric(obCmd);
35
+ registerAnalytics(obCmd);
36
+ }
37
+ // ── log ──
38
+ function registerLog(parent) {
39
+ const cmd = parent
40
+ .command("log")
41
+ .description("查询线上运行日志(按时间倒序,分页)")
42
+ .addOption((0, shared_1.appIdOption)().hideHelp())
43
+ .addOption(new commander_1.Option("--level <level>", "日志级别(大小写不敏感)")
44
+ .choices(["DEBUG", "INFO", "WARN", "ERROR"])
45
+ .argParser((0, shared_1.caseInsensitiveChoice)(["DEBUG", "INFO", "WARN", "ERROR"])))
46
+ .option("--since <time>", "开始时间")
47
+ .option("--until <time>", "截止时间")
48
+ .option("--log-id <id>", "按 log ID 过滤")
49
+ .option("--trace-id <id>", "按 trace ID 过滤")
50
+ .option("--grep <pattern>", "按关键字模糊搜索 body")
51
+ .option("--module <name>", "按模块名过滤")
52
+ .option("--user-id <user-id>", "按触发用户 ID 过滤")
53
+ .option("--page <path>", "按页面路径过滤")
54
+ .option("--api <path>", "按接口路径过滤")
55
+ .option("--min-duration <ms>", "最小耗时过滤(毫秒)")
56
+ .option("--max-duration <ms>", "最大耗时过滤(毫秒)")
57
+ .option("--limit <n>", "返回条数上限(1~100)", parseLimit, 50)
58
+ .option("--cursor <token>", "下一页游标,从上一次返回的 next_cursor 取值")
59
+ .addHelpText("after", `${COMMON_TIME_HELP}
60
+ JSON 输出
61
+ {"data": [...], "next_cursor": "...", "has_more": true|false}
62
+
63
+ 示例
64
+ $ miaoda observability log --since 1h --level error --json
65
+ $ miaoda observability log --log-id log_abc123 --json
66
+ $ miaoda observability log --trace-id 140ebb5ac9b... --json
67
+ $ miaoda observability log --api /api/orders --min-duration 200 --json
68
+ `);
69
+ cmd.action((0, shared_1.withHelp)(cmd, async (rawOpts) => {
70
+ (0, shared_1.validateTimeOptions)(rawOpts, "since", "until");
71
+ (0, shared_1.rejectCliOverride)(cmd, "appId");
72
+ await (0, index_1.handleObservabilityLog)({
73
+ appId: rawOpts.appId,
74
+ level: rawOpts.level,
75
+ since: rawOpts.since,
76
+ until: rawOpts.until,
77
+ logId: rawOpts.logId,
78
+ traceId: rawOpts.traceId,
79
+ grep: rawOpts.grep,
80
+ module: rawOpts.module,
81
+ userId: rawOpts.userId,
82
+ page: rawOpts.page,
83
+ api: rawOpts.api,
84
+ minDuration: rawOpts.minDuration,
85
+ maxDuration: rawOpts.maxDuration,
86
+ limit: rawOpts.limit,
87
+ cursor: rawOpts.cursor,
88
+ });
89
+ }));
90
+ }
91
+ // ── trace ──
92
+ function registerTrace(parent) {
93
+ const traceCmd = parent.command("trace").description("链路追踪:列表 / 详情");
94
+ traceCmd.action(() => {
95
+ traceCmd.outputHelp();
96
+ });
97
+ const listCmd = traceCmd
98
+ .command("list")
99
+ .description("查询线上链路列表(按链路时间倒序,分页)")
100
+ .addOption((0, shared_1.appIdOption)().hideHelp())
101
+ .option("--since <time>", "开始时间")
102
+ .option("--until <time>", "截止时间")
103
+ .option("--trace-id <id>", "按 trace ID 过滤")
104
+ .option("--root-span <span-name>", "按入口节点关键词过滤")
105
+ .option("--user-id <user-id>", "按触发用户 ID 过滤")
106
+ .option("--limit <n>", "返回条数上限(1~100)", parseLimit, 50)
107
+ .option("--cursor <token>", "下一页游标")
108
+ .addHelpText("after", `${COMMON_TIME_HELP}
109
+ JSON 输出
110
+ {"data": [...], "next_cursor": "...", "has_more": true|false}
111
+
112
+ 示例
113
+ $ miaoda observability trace list --since 1h --json
114
+ $ miaoda observability trace list --root-span api-gateway --limit 20 --json
115
+ `);
116
+ listCmd.action((0, shared_1.withHelp)(listCmd, async (rawOpts) => {
117
+ (0, shared_1.validateTimeOptions)(rawOpts, "since", "until");
118
+ (0, shared_1.rejectCliOverride)(listCmd, "appId");
119
+ await (0, index_1.handleObservabilityTraceList)({
120
+ appId: rawOpts.appId,
121
+ since: rawOpts.since,
122
+ until: rawOpts.until,
123
+ traceId: rawOpts.traceId,
124
+ rootSpan: rawOpts.rootSpan,
125
+ userId: rawOpts.userId,
126
+ limit: rawOpts.limit,
127
+ cursor: rawOpts.cursor,
128
+ });
129
+ }));
130
+ const getCmd = traceCmd
131
+ .command("get")
132
+ .description("查询指定链路的完整详情")
133
+ .argument("<trace-id>", "链路 ID")
134
+ .addOption((0, shared_1.appIdOption)().hideHelp())
135
+ .option("--with-log-severity-count", "返回每个 Span 各日志级别的数量", false)
136
+ .addHelpText("after", `
137
+ JSON 输出
138
+ {"data": {"spans": [...], "isBreak": false}}
139
+
140
+ 示例
141
+ $ miaoda observability trace get 140ebb5ac9b55ed50d6ed1090cad4d --json
142
+
143
+ # 报错:链路不存在
144
+ $ miaoda observability trace get not-exist
145
+ Error: Failed to get trace: 500 ...
146
+ hint: 检查 trace-id 是否正确,或链路已超出保留时长
147
+ `);
148
+ getCmd.action((0, shared_1.withHelp)(getCmd, async (traceId, rawOpts) => {
149
+ (0, shared_1.rejectCliOverride)(getCmd, "appId");
150
+ await (0, index_1.handleObservabilityTraceGet)({
151
+ traceId,
152
+ appId: rawOpts.appId,
153
+ withLogSeverityCount: rawOpts.withLogSeverityCount,
154
+ });
155
+ }));
156
+ }
157
+ // ── metric ──
158
+ function registerMetric(parent) {
159
+ const cmd = parent
160
+ .command("metric")
161
+ .description("查询监控指标:requests / latency / cpu / memory")
162
+ .argument("<metric-name>", "指标名:requests | latency | cpu | memory")
163
+ .addOption((0, shared_1.appIdOption)().hideHelp())
164
+ .option("--page <path>", "按页面路径过滤(仅对 requests/latency 生效)")
165
+ .option("--api <path>", "按接口路径过滤(仅对 requests/latency 生效)")
166
+ .option("--series <name>", "过滤图表中的某条线:latency 取 p50/p99;requests 取 total/error;缺省返回所有相关线")
167
+ .option("--since <time>", "开始时间")
168
+ .option("--until <time>", "截止时间")
169
+ .addOption(new commander_1.Option("--down-sample <duration>", "降采样粒度(1m=1分钟 / 1h=1小时 / 1d=1天,大小写不敏感)")
170
+ .choices(["1m", "1h", "1d"])
171
+ .argParser((0, shared_1.caseInsensitiveChoice)(["1m", "1h", "1d"]))
172
+ .default("1m"))
173
+ .addHelpText("after", `${COMMON_TIME_HELP}
174
+ JSON 输出
175
+ {"data": [{"metricName": "...", "dimensions": {...}, "dataPoints": [...]}], "next_cursor": null, "has_more": false}
176
+
177
+ 示例
178
+ $ miaoda observability metric latency --since 1h --json
179
+ $ miaoda observability metric latency --since 1h --series p99 --json
180
+ $ miaoda observability metric requests --api /api/users --json
181
+ $ miaoda observability metric cpu --since 1d --down-sample 1d --json
182
+ `);
183
+ cmd.action((0, shared_1.withHelp)(cmd, async (metricName, rawOpts) => {
184
+ (0, shared_1.validateTimeOptions)(rawOpts, "since", "until");
185
+ (0, shared_1.rejectCliOverride)(cmd, "appId");
186
+ await (0, index_1.handleObservabilityMetric)({
187
+ metricName,
188
+ appId: rawOpts.appId,
189
+ page: rawOpts.page,
190
+ api: rawOpts.api,
191
+ series: rawOpts.series,
192
+ since: rawOpts.since,
193
+ until: rawOpts.until,
194
+ downSample: rawOpts.downSample,
195
+ });
196
+ }));
197
+ }
198
+ // ── analytics ──
199
+ function registerAnalytics(parent) {
200
+ const cmd = parent
201
+ .command("analytics")
202
+ .description("查询运营指标:users(用户数)/ page-view(页面访问)")
203
+ .argument("<analytics-name>", "指标名:users | page-view")
204
+ .addOption((0, shared_1.appIdOption)().hideHelp())
205
+ .option("--page <path>", "按页面路径过滤(仅对 page-view 生效)")
206
+ .option("--series <name>", "过滤图表中的某条线:users 取 active/new/total(兼容 active-users/new-users/total-users);page-view 取 all/desktop/mobile(兼容 all-view/desktop-view/mobile-view)")
207
+ .option("--since <time>", "开始时间")
208
+ .option("--until <time>", "截止时间")
209
+ .option("--granularity <duration>", "时间粒度:day | week | month", "day")
210
+ .addHelpText("after", `${COMMON_TIME_HELP}
211
+ JSON 输出
212
+ {"data": [{"metricType": "...", "points": [{"timestampNs": "...", "value": ..., "dimensions": {...}}]}], "next_cursor": null, "has_more": false}
213
+
214
+ 示例
215
+ $ miaoda observability analytics users --json # 同时返回 active/new/total 三条线
216
+ $ miaoda observability analytics users --series new --since 7d --json
217
+ $ miaoda observability analytics page-view --granularity week --json
218
+ `);
219
+ cmd.action((0, shared_1.withHelp)(cmd, async (analyticsName, rawOpts) => {
220
+ (0, shared_1.validateTimeOptions)(rawOpts, "since", "until");
221
+ (0, shared_1.rejectCliOverride)(cmd, "appId");
222
+ await (0, index_1.handleObservabilityAnalytics)({
223
+ analyticsName,
224
+ appId: rawOpts.appId,
225
+ env: rawOpts.env,
226
+ page: rawOpts.page,
227
+ series: rawOpts.series,
228
+ since: rawOpts.since,
229
+ until: rawOpts.until,
230
+ granularity: rawOpts.granularity,
231
+ });
232
+ }));
233
+ }
234
+ function parseLimit(value) {
235
+ const n = Number(value);
236
+ if (!Number.isFinite(n)) {
237
+ throw new Error(`--limit 必须是数字,收到 '${value}'`);
238
+ }
239
+ return n;
240
+ }
@@ -58,7 +58,9 @@ JSON 输出
58
58
  Error: Invalid plugin name format: bad-name. Expected: @scope/name or @scope/name@version
59
59
  hint: 示例:@demo/example-plugin 或 @demo/example-plugin@1.2.3
60
60
  `)
61
- .action(async (names) => { await (0, index_1.handlePluginInstall)({ names }); });
61
+ .action(async (names) => {
62
+ await (0, index_1.handlePluginInstall)({ names });
63
+ });
62
64
  pluginCmd
63
65
  .command("update")
64
66
  .description("把已安装插件升级到 latest 版本")
@@ -91,7 +93,9 @@ JSON 输出
91
93
  $ miaoda plugin update @demo/not-installed --json
92
94
  {"updated":[],"skipped":[],"notInstalled":["@demo/not-installed"],"failed":[]}
93
95
  `)
94
- .action(async (names) => { await (0, index_1.handlePluginUpdate)({ names }); });
96
+ .action(async (names) => {
97
+ await (0, index_1.handlePluginUpdate)({ names });
98
+ });
95
99
  pluginCmd
96
100
  .command("remove")
97
101
  .description("从当前项目移除一个已安装的插件")
@@ -115,7 +119,9 @@ JSON 输出
115
119
  Error: Plugin @demo/not-installed is not installed
116
120
  hint: 运行 miaoda plugin list-packages 查看已安装插件
117
121
  `)
118
- .action((name) => { (0, index_1.handlePluginRemove)({ name }); });
122
+ .action((name) => {
123
+ (0, index_1.handlePluginRemove)({ name });
124
+ });
119
125
  pluginCmd
120
126
  .command("init")
121
127
  .description("按 package.json 的 actionPlugins 批量安装所有插件")
@@ -146,7 +152,9 @@ JSON 输出
146
152
  Error: package.json not found in current directory
147
153
  hint: 在应用项目根目录运行
148
154
  `)
149
- .action(async () => { await (0, index_1.handlePluginInit)(); });
155
+ .action(async () => {
156
+ await (0, index_1.handlePluginInit)();
157
+ });
150
158
  pluginCmd
151
159
  .command("list")
152
160
  .description("列出当前项目的 capability 实例(./server/capabilities/*.json)")
@@ -178,7 +186,9 @@ JSON 输出
178
186
  Error: server/capabilities directory not found
179
187
  hint: 当前目录必须是含 server/capabilities/ 的应用项目
180
188
  `)
181
- .action(async (opts) => { await (0, index_1.handlePluginList)(opts); });
189
+ .action(async (opts) => {
190
+ await (0, index_1.handlePluginList)(opts);
191
+ });
182
192
  pluginCmd
183
193
  .command("list-packages")
184
194
  .description("列出 package.json actionPlugins 里已声明的插件包")
@@ -201,5 +211,7 @@ JSON 输出
201
211
  Error: package.json not found in current directory
202
212
  hint: 在应用项目根目录运行
203
213
  `)
204
- .action(() => { (0, index_1.handlePluginListPlugins)(); });
214
+ .action(() => {
215
+ (0, index_1.handlePluginListPlugins)();
216
+ });
205
217
  }
@@ -1,11 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.appIdOption = appIdOption;
4
+ exports.branchOption = branchOption;
3
5
  exports.softRequiredOption = softRequiredOption;
4
6
  exports.resolveAppId = resolveAppId;
5
7
  exports.withHelp = withHelp;
6
8
  exports.failArgs = failArgs;
9
+ exports.caseInsensitiveChoice = caseInsensitiveChoice;
10
+ exports.validateTimeOptions = validateTimeOptions;
11
+ exports.rejectCliOverride = rejectCliOverride;
7
12
  const commander_1 = require("commander");
8
13
  const error_1 = require("../../utils/error");
14
+ const time_1 = require("../../utils/time");
15
+ /** --app-id option,需要应用上下文的命令自行 .addOption(appIdOption()) */
16
+ function appIdOption() {
17
+ return new commander_1.Option("--app-id <id>", "指定目标应用").env("MIAODA_APP_ID");
18
+ }
19
+ function branchOption() {
20
+ return new commander_1.Option("--branch <branch>", "分支(优先级:--branch > 当前仓库 HEAD 分支;非 git 目录回退应用默认分支)").env("LOCAL_MOCK_MIAODA_DEPLOY_BRANCH");
21
+ }
9
22
  /**
10
23
  * soft-required: Commander 类型上 optional,runtime 校验必填。
11
24
  */
@@ -22,18 +35,20 @@ function resolveAppId(opts) {
22
35
  const id = opts.appId ?? process.env.MIAODA_APP_ID ?? process.env.app_id;
23
36
  if (!id) {
24
37
  throw new error_1.AppError("APP_ID_MISSING", "未指定应用", {
25
- next_actions: [
26
- "设置 export MIAODA_APP_ID=<id>",
27
- ],
38
+ next_actions: ["设置 export MIAODA_APP_ID=<id>"],
28
39
  });
29
40
  }
30
41
  return id;
31
42
  }
32
- /** 包裹 handler,缺 soft-required 参数时打 help 并退出 */
43
+ /**
44
+ * 包裹 handler,缺 soft-required 参数 / 自定义校验失败时打 help 并退出。
45
+ *
46
+ * 兼容带位置参数的 action 签名(如 `(arg1: string, opts) => ...`)。
47
+ */
33
48
  function withHelp(cmd, handler) {
34
- return async (opts) => {
49
+ return async (...args) => {
35
50
  try {
36
- await handler(opts);
51
+ await handler(...args);
37
52
  }
38
53
  catch (err) {
39
54
  if (err instanceof error_1.AppError && err.code === "ARGS_INVALID") {
@@ -50,3 +65,64 @@ function withHelp(cmd, handler) {
50
65
  function failArgs(message) {
51
66
  throw new error_1.AppError("ARGS_INVALID", message);
52
67
  }
68
+ /**
69
+ * 大小写不敏感的 choice argParser:把用户输入按 lowerCase 匹配回 canonical 数组里
70
+ * 的同名值(保留 canonical 大小写),未命中抛 Commander 的 InvalidArgumentError
71
+ * (exit code 1,自带友好错误)。
72
+ *
73
+ * 必须先 .choices(canonical)、再 .argParser()——Commander 内部 .choices() 会
74
+ * 重置 parseArg,反过来调会让 argParser 失效。.choices() 仅留给 help 渲染
75
+ * "choices: A, B, C",实际白名单校验由 argParser 接管。
76
+ *
77
+ * new Option("--level <level>", "日志级别(不区分大小写)")
78
+ * .choices(["DEBUG", "INFO", "WARN", "ERROR"])
79
+ * .argParser(caseInsensitiveChoice(["DEBUG", "INFO", "WARN", "ERROR"]));
80
+ */
81
+ function caseInsensitiveChoice(canonical) {
82
+ const map = new Map(canonical.map((v) => [v.toLowerCase(), v]));
83
+ return (raw) => {
84
+ const hit = map.get(raw.toLowerCase());
85
+ if (hit === undefined) {
86
+ throw new commander_1.InvalidArgumentError(`Allowed choices are ${canonical.join(", ")} (case-insensitive).`);
87
+ }
88
+ return hit;
89
+ };
90
+ }
91
+ /**
92
+ * --since / --until 等时间参数的 action 阶段校验。
93
+ *
94
+ * Commander 的 argParser 会在 action 前直接按 parser error 退出(exit 1),
95
+ * 绕过 withHelp 的 ARGS_INVALID → exit 2 路径;所以时间参数在 action 内先
96
+ * 校验一遍,再把原始字符串交给 handler 解析成接口需要的单位。
97
+ */
98
+ function validateTimeOptions(opts, ...names) {
99
+ for (const name of names) {
100
+ const value = opts[name];
101
+ if (value === undefined)
102
+ continue;
103
+ if (typeof value !== "string") {
104
+ failArgs(`--${name.replace(/([A-Z])/g, "-$1").toLowerCase()} 必须是时间字符串`);
105
+ }
106
+ (0, time_1.parseTimeToMs)(value);
107
+ }
108
+ }
109
+ /**
110
+ * 拒绝 CLI 显式覆盖:用于 hideHelp() + .env() 的"沙箱注入参数"(如 --app-id / --branch)。
111
+ *
112
+ * Commander 的 getOptionValueSource() 区分来源(cli / env / default / config / undefined);
113
+ * 用户在 CLI 上显式传时 source === "cli",此时抛 ARGS_INVALID(exit 2 + help)。
114
+ *
115
+ * 用法:在 action 头部一行调用——
116
+ * cmd.action(withHelp(cmd, async (rawOpts) => {
117
+ * rejectCliOverride(cmd, "appId", "branch");
118
+ * ...
119
+ * }));
120
+ */
121
+ function rejectCliOverride(cmd, ...optNames) {
122
+ for (const name of optNames) {
123
+ if (cmd.getOptionValueSource(name) === "cli") {
124
+ const flag = "--" + name.replace(/([A-Z])/g, "-$1").toLowerCase();
125
+ failArgs(`${flag} 由沙箱/本地配置注入,不允许显式传递`);
126
+ }
127
+ }
128
+ }
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.handleAppGet = handleAppGet;
37
+ const api = __importStar(require("../../../api/index"));
38
+ const output_1 = require("../../../utils/output");
39
+ const shared_1 = require("../../../cli/commands/shared");
40
+ const index_1 = require("../../../api/app/index");
41
+ /** miaoda app get [--app-id <id>] */
42
+ async function handleAppGet(opts) {
43
+ const appID = (0, shared_1.resolveAppId)({ appId: opts.appId });
44
+ const resp = await api.app.getAppInfo(appID);
45
+ // BAM 在 status_code=0 时 data 字段含 appInfo;不存在则 fallback 空对象
46
+ const meta = resp.appInfo?.appMeta ?? {};
47
+ (0, output_1.emit)({ data: meta, next_cursor: null, has_more: false }, index_1.appMetaSchema);
48
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handleAppUpdate = exports.handleAppGet = void 0;
4
+ var get_1 = require("./get");
5
+ Object.defineProperty(exports, "handleAppGet", { enumerable: true, get: function () { return get_1.handleAppGet; } });
6
+ var update_1 = require("./update");
7
+ Object.defineProperty(exports, "handleAppUpdate", { enumerable: true, get: function () { return update_1.handleAppUpdate; } });