@lark-apaas/miaoda-cli 0.1.0-alpha.097a394 → 0.1.0-alpha.267b637

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.
@@ -7,20 +7,22 @@ exports.exportData = exportData;
7
7
  const http_1 = require("../../utils/http");
8
8
  const error_1 = require("../../utils/error");
9
9
  const client_1 = require("./client");
10
- /** dataloom 默认 dbBranch —— 单环境应用均传 main */
11
- const DEFAULT_DB_BRANCH = "main";
12
- // ── db sql → InnerExecuteSQL ──
10
+ // CLI 不再为 dbBranch 设默认值:
11
+ // 用户没传 --env 就完全不携带 dbBranch query 参数,由后端 admin-inner 中间件
12
+ // 按 workspace 多环境状态决定(多环境 → dev / 单环境 → main)。
13
+ // 这样可以避免单环境应用被强行打到 main 之外、或多环境应用被默认打到 main 上线库。
14
+ // ── db sql → InnerAdminExecuteSQL ──
13
15
  /**
14
- * 执行 SQL。
15
- * 后端:POST /v1/app/{appId}/dataloom/sql?dbBranch=main
16
+ * 执行 SQL(admin-inner)。
17
+ * 后端:POST /v1/dataloom/app/{appId}/db/sql?dbBranch=main
16
18
  *
17
19
  * 返回所有 results[](多条语句时每条一项);CLI 侧按 PRD 仅取最后一条展示,
18
20
  * 但 API 层保留完整列表以便测试和高级用法。
19
21
  */
20
22
  async function execSql(opts) {
21
23
  const client = (0, http_1.getHttpClient)();
22
- const url = (0, client_1.buildInnerUrl)(opts.appId, "/sql", {
23
- dbBranch: opts.dbBranch ?? DEFAULT_DB_BRANCH,
24
+ const url = (0, client_1.buildInnerUrl)(opts.appId, "/db/sql", {
25
+ dbBranch: opts.dbBranch,
24
26
  });
25
27
  const response = await client.post(url, { sql: opts.sql });
26
28
  if (!response.ok) {
@@ -42,18 +44,18 @@ async function execSql(opts) {
42
44
  }
43
45
  // ── db schema → InnerGetSchema ──
44
46
  /**
45
- * 查询 schema。
46
- * 后端:GET /v1/app/{appId}/dataloom/schema?format=schema|ddl&tableNames=...&includeStats=...&dbBranch=main
47
+ * 查询 schema(admin-inner)。
48
+ * 后端:GET /v1/dataloom/app/{appId}/db/schema?format=schema|ddl&tableNames=...&includeStats=...&dbBranch=main
47
49
  *
48
50
  * 返回 body.data(含 `schema` 或 `ddl`)供 handler 使用。
49
51
  */
50
52
  async function getSchema(opts) {
51
53
  const client = (0, http_1.getHttpClient)();
52
- const url = (0, client_1.buildInnerUrl)(opts.appId, "/schema", {
54
+ const url = (0, client_1.buildInnerUrl)(opts.appId, "/db/schema", {
53
55
  format: opts.format ?? "schema",
54
56
  tableNames: opts.tableNames,
55
57
  includeStats: opts.includeStats ? "true" : undefined,
56
- dbBranch: opts.dbBranch ?? DEFAULT_DB_BRANCH,
58
+ dbBranch: opts.dbBranch,
57
59
  });
58
60
  const response = await client.get(url);
59
61
  if (!response.ok) {
@@ -71,28 +73,30 @@ async function getSchema(opts) {
71
73
  const body = (await response.json());
72
74
  return (0, client_1.extractData)(body);
73
75
  }
74
- // ── db data import → InnerImportData ──
76
+ // ── db data import → InnerAdminImportData ──
75
77
  /**
76
78
  * 导入文件。
77
- * 后端:POST /v1/app/{appId}/dataloom/data/import?tableName=...&format=csv|json&dbBranch=main
79
+ * 后端:POST /v1/dataloom/app/{appId}/data/import
78
80
  *
79
- * Body 为原始文件字节(不走 JSON envelope)。
81
+ * 全字段走 JSON body envelope(idl-larkgw 36125a2f):
82
+ * {tableName, format, records, dbBranch?}
83
+ *
84
+ * `records` 字段携带 CSV / JSON 文本内容(utf8 字符串),与 dataloom 上
85
+ * Import/ExportAdminRecords 命名风格对齐。CLI 端把 Buffer 解码成 utf8
86
+ * 字符串后塞进 envelope 即可。
80
87
  */
81
88
  async function importData(opts) {
82
89
  const client = (0, http_1.getHttpClient)();
83
- const url = (0, client_1.buildInnerUrl)(opts.appId, "/data/import", {
90
+ const url = (0, client_1.buildInnerUrl)(opts.appId, "/data/import");
91
+ const reqBody = {
84
92
  tableName: opts.tableName,
85
93
  format: opts.format,
86
- dbBranch: opts.dbBranch ?? DEFAULT_DB_BRANCH,
87
- });
88
- const contentType = opts.format === "csv" ? "text/csv" : "application/json";
89
- const ab = opts.body.buffer.slice(opts.body.byteOffset, opts.body.byteOffset + opts.body.byteLength);
90
- const response = await client.request({
91
- method: "POST",
92
- url,
93
- headers: { "Content-Type": contentType },
94
- body: ab,
95
- });
94
+ records: opts.body.toString("utf8"),
95
+ };
96
+ if (opts.dbBranch !== undefined && opts.dbBranch !== "") {
97
+ reqBody.dbBranch = opts.dbBranch;
98
+ }
99
+ const response = await client.post(url, reqBody);
96
100
  if (!response.ok) {
97
101
  let body = null;
98
102
  try {
@@ -105,31 +109,35 @@ async function importData(opts) {
105
109
  (0, client_1.extractData)(body);
106
110
  throw new error_1.HttpError(response.status, url, `Failed to import data: ${String(response.status)} ${response.statusText}`);
107
111
  }
108
- // 后端 InnerImportData 响应里 data 直接返 {tableName, rows, durationMs}
112
+ // 后端 InnerAdminImportData 响应里 data 直接返 {tableName, recordCount, durationMs}
109
113
  const body = (await response.json());
110
114
  const data = (0, client_1.extractData)(body);
111
115
  return {
112
116
  tableName: data.tableName ?? opts.tableName,
113
- rows: data.rows ?? 0,
117
+ recordCount: data.recordCount ?? 0,
114
118
  durationMs: data.durationMs ?? 0,
115
119
  };
116
120
  }
117
- // ── db data export → InnerExportData ──
121
+ // ── db data export → InnerAdminExportData ──
118
122
  /**
119
123
  * 导出数据。
120
- * 后端:POST /v1/app/{appId}/dataloom/data/export?tableName=...&format=csv|json&dbBranch=main
124
+ * 后端:POST /v1/dataloom/app/{appId}/data/export?tableName=...&format=csv|json&limit=5000&dbBranch=main
121
125
  *
122
- * 响应 body 为原始 CSV/JSON 字节(不走 envelope)。错误仍通过 HTTP 4xx/5xx + BaseResp 传达。
126
+ * 所有参数(含 limit)均按 IDL `api.query` 走 query string;HTTP 方法是 POST(对齐
127
+ * inner_api 网关插件路由约定,与 InnerAdminExecuteSQL 同 method)。请求体为空。
128
+ * 响应 body 为原始 CSV/JSON 字节,RecordCount 通过响应头 `X-Miaoda-Record-Count`
129
+ * 回传,错误仍走 HTTP 4xx/5xx + envelope。
123
130
  */
124
131
  async function exportData(opts) {
125
132
  const client = (0, http_1.getHttpClient)();
126
133
  const url = (0, client_1.buildInnerUrl)(opts.appId, "/data/export", {
127
134
  tableName: opts.tableName,
128
135
  format: opts.format,
129
- dbBranch: opts.dbBranch ?? DEFAULT_DB_BRANCH,
136
+ limit: String(opts.limit ?? 5000),
137
+ dbBranch: opts.dbBranch,
130
138
  });
131
- const reqBody = { limit: opts.limit ?? 5000 };
132
- const response = await client.post(url, reqBody);
139
+ // POST + 空 body:所有业务参数都在 query 里
140
+ const response = await client.request({ method: "POST", url });
133
141
  if (!response.ok) {
134
142
  // 错误路径:body 是 JSON envelope
135
143
  let body = null;
@@ -143,7 +151,8 @@ async function exportData(opts) {
143
151
  (0, client_1.extractData)(body);
144
152
  throw new error_1.HttpError(response.status, url, `Failed to export data: ${String(response.status)} ${response.statusText}`);
145
153
  }
146
- // 成功路径:响应 body 是原始 CSV/JSON 字节
154
+ // 成功路径:响应 body 通常是原始 CSV/JSON 字节,但部分错误场景下网关会返
155
+ // HTTP 200 + JSON envelope(status_code != "0"),需要在这里嗅探兜底。
147
156
  const contentType = response.headers.get("Content-Type") ??
148
157
  (opts.format === "csv" ? "text/csv" : "application/json");
149
158
  const ab = await response.arrayBuffer();
@@ -151,10 +160,33 @@ async function exportData(opts) {
151
160
  if (buf.length === 0) {
152
161
  throw new error_1.AppError("INTERNAL_DB_ERROR", "Empty export response body");
153
162
  }
163
+ // Envelope sniff:HTTP 200 + Content-Type 为 application/json + body 解析得到
164
+ // InnerEnvelope 且 status_code 非 "0" 时,按业务错误抛出。
165
+ // 仅 CSV 格式做 sniff —— JSON 格式正常成功响应也是 application/json,会误判。
166
+ if (opts.format === "csv" && /application\/json/i.test(contentType)) {
167
+ try {
168
+ const parsed = JSON.parse(buf.toString("utf8"));
169
+ if (parsed.status_code != null && parsed.status_code !== "0") {
170
+ // 复用 extractData 的错误映射逻辑(throw AppError)
171
+ (0, client_1.extractData)(parsed);
172
+ }
173
+ }
174
+ catch (err) {
175
+ // 已经被 extractData 抛成 AppError → 透传;否则 JSON.parse 失败说明 body
176
+ // 真的是 CSV 文本,继续按成功流程走
177
+ if (err instanceof error_1.AppError)
178
+ throw err;
179
+ }
180
+ }
181
+ // 后端通过响应头回传记录数(避免污染 body);header 缺失或解析失败 → undefined
182
+ const recordCountHeader = response.headers.get("X-Miaoda-Record-Count");
183
+ const parsedCount = recordCountHeader != null ? Number(recordCountHeader) : NaN;
184
+ const recordCount = Number.isFinite(parsedCount) && parsedCount >= 0 ? parsedCount : undefined;
154
185
  return {
155
186
  tableName: opts.tableName,
156
187
  format: opts.format,
157
188
  contentType,
158
189
  body: buf,
190
+ recordCount,
159
191
  };
160
192
  }
@@ -19,21 +19,27 @@ function ensureInnerSuccess(body) {
19
19
  const code = body.status_code ?? body.ErrorCode ?? "0";
20
20
  if (code === "0" || code === "")
21
21
  return;
22
- const message = body.error_msg ?? body.ErrorMessage ?? `dataloom API error [${code}]`;
22
+ const message = stripPgPrefix(body.error_msg ?? body.ErrorMessage ?? `dataloom API error [${code}]`);
23
+ // PRD 多语句失败:后端在 envelope 顶层透出 errorStatementIndex(从 0 起计),
24
+ // 单语句 / 单元执行不会带这个字段。下面的 AppError 都把它带上,让最终
25
+ // CLI JSON envelope 写到 error.statement_index。
26
+ const stmtIdx = typeof body.errorStatementIndex === "number" ? body.errorStatementIndex : undefined;
23
27
  // k_dl_1300002 是 PG 执行透传错误;error_msg 里常带 SQLSTATE,优先按 SQLSTATE 映射
24
28
  if (code === "k_dl_1300002") {
25
29
  const sqlstate = extractSqlstate(message);
26
30
  if (sqlstate && exports.SQLSTATE_MAP[sqlstate]) {
27
- throw new error_1.AppError(exports.SQLSTATE_MAP[sqlstate], message);
31
+ throw new error_1.AppError(exports.SQLSTATE_MAP[sqlstate], message, { statement_index: stmtIdx });
28
32
  }
29
33
  }
30
34
  // k_dl_1600000 是 dataloom 通用参数错误,不能整体映射;
31
- // 只有 message 以 "Invalid DB Branch" 开头的情况对应"用户传了 --env 但 dbBranch 不存在 / 多环境未初始化",
32
- // 按技术方案固定映射为 MULTI_ENV_NOT_INITIALIZED(含固定 message 与 hint)。
35
+ // message 以 "Invalid DB Branch" 开头的两种触发场景:
36
+ // 1) 单环境应用使用 --env(多环境未初始化)
37
+ // 2) 多环境应用传入了不存在的 env 名(如 --env staging)
38
+ // 两者外部表象一致:dbBranch 在 db_branch 表里查不到,固定映射为 MULTI_ENV_NOT_INITIALIZED。
33
39
  if (code === "k_dl_1600000" && message.startsWith("Invalid DB Branch")) {
34
40
  throw new error_1.AppError("MULTI_ENV_NOT_INITIALIZED", "--env is not available (multi-env not initialized)", {
35
41
  next_actions: [
36
- "Current app uses a single database for dev and production. Run `miaoda db migration init` to set up multi-env.",
42
+ "Verify the --env value matches an existing dbBranch.",
37
43
  ],
38
44
  });
39
45
  }
@@ -42,10 +48,19 @@ function ensureInnerSuccess(body) {
42
48
  if (mapped) {
43
49
  throw new error_1.AppError(mapped.code, mapped.message ?? message, {
44
50
  next_actions: mapped.hint ? [mapped.hint] : undefined,
51
+ statement_index: stmtIdx,
45
52
  });
46
53
  }
47
54
  // 兜底:dataloom 未映射的 code 原样透传
48
- throw new error_1.AppError(`DB_API_${code}`, message);
55
+ throw new error_1.AppError(`DB_API_${code}`, message, { statement_index: stmtIdx });
56
+ }
57
+ /**
58
+ * 剥掉 PG 透传错误的 "ERROR:" 前缀:CLI 输出本身就会前缀 "Error:",
59
+ * 不去掉就会变成 `Error: ERROR: relation ...` 双重前缀,PRD 不要这种冗余。
60
+ * 大小写敏感,只匹配 PG 标准格式。
61
+ */
62
+ function stripPgPrefix(msg) {
63
+ return msg.replace(/^ERROR:\s*/, "");
49
64
  }
50
65
  /** 从 PG 执行错误消息里提取 "(SQLSTATE XXXXX)"。 */
51
66
  function extractSqlstate(msg) {
@@ -89,11 +104,19 @@ function extractData(body) {
89
104
  return body.data;
90
105
  }
91
106
  /**
92
- * 组装 `/v1/app/{appId}/dataloom/...` URL。
107
+ * 组装 `/v1/dataloom/app/{appId}/...` URL(admin-inner 链路)。
108
+ *
109
+ * 后端 IDL 已把 dataloom 的 4 个 inner 接口切到管理态(ForceAdminKctx),
110
+ * 路径前缀也统一改为 `/v1/dataloom/app/:appID/...`:
111
+ * - sql: POST /v1/dataloom/app/{appId}/db/sql
112
+ * - schema: GET /v1/dataloom/app/{appId}/db/schema
113
+ * - import: POST /v1/dataloom/app/{appId}/data/import
114
+ * - export: POST /v1/dataloom/app/{appId}/data/export
115
+ * 调用方传入的 path 已包含 `/db` / `/data` 中段,这里只负责拼前缀和 query。
93
116
  */
94
117
  function buildInnerUrl(appId, path, query) {
95
118
  const normalized = path.startsWith("/") ? path : `/${path}`;
96
- let url = `/v1/app/${encodeURIComponent(appId)}/dataloom${normalized}`;
119
+ let url = `/v1/dataloom/app/${encodeURIComponent(appId)}${normalized}`;
97
120
  if (query) {
98
121
  const usp = new URLSearchParams();
99
122
  for (const [k, v] of Object.entries(query)) {
@@ -27,16 +27,23 @@ function parseSqlResult(r) {
27
27
  recordCount: r.recordCount ?? rows.length,
28
28
  };
29
29
  }
30
- if (r.sqlType === "INSERT" || r.sqlType === "UPDATE" || r.sqlType === "DELETE") {
30
+ if (r.sqlType === "INSERT" ||
31
+ r.sqlType === "UPDATE" ||
32
+ r.sqlType === "DELETE" ||
33
+ r.sqlType === "MERGE" ||
34
+ r.sqlType === "DML") {
31
35
  const affected = r.affectedRows ?? extractRowCount(r.data);
32
36
  return {
33
37
  kind: "dml",
38
+ // 上面已 narrow,这里 cast 是为了 SqlType 联合里的 (string & {}) 让 TS 无法
39
+ // 自动收窄到字面量集合,不影响运行时安全
34
40
  sqlType: r.sqlType,
35
41
  affectedRows: affected,
36
42
  };
37
43
  }
38
- // DDL or unknown
39
- return { kind: "ddl" };
44
+ // DDL or unknown — sqlType 透传后端给的细粒度(CREATE_TABLE / DROP_TABLE / ...
45
+ // / 笼统 "DDL"),CLI JSON 输出直接当 command 用
46
+ return { kind: "ddl", sqlType: r.sqlType };
40
47
  }
41
48
  /** DML 的 data 通常是 `[{"rowCount": N}]`;兜底从这里读影响行数。 */
42
49
  function extractRowCount(data) {
@@ -82,7 +89,6 @@ function toSummary(t, stats) {
82
89
  columns: (t.fields ?? []).length,
83
90
  estimated_row_count: typeof stats?.estimatedRowCount === "number" ? stats.estimatedRowCount : null,
84
91
  size_bytes: typeof stats?.sizeBytes === "number" ? stats.sizeBytes : null,
85
- updated_at: t.updatedAt,
86
92
  };
87
93
  }
88
94
  /**
@@ -118,8 +124,6 @@ function toDetail(t, stats) {
118
124
  indexes: rawIndexes.map(toIndex),
119
125
  estimated_row_count: typeof stats?.estimatedRowCount === "number" ? stats.estimatedRowCount : null,
120
126
  size_bytes: typeof stats?.sizeBytes === "number" ? stats.sizeBytes : null,
121
- created_at: t.createdAt,
122
- updated_at: t.updatedAt,
123
127
  };
124
128
  }
125
129
  function toColumn(f) {
@@ -36,7 +36,7 @@ function extractEnvelope(body) {
36
36
  // ── list ──
37
37
  /** 底层单次 list 调用(一页)。支持 filterExpr / sortBy 下推。 */
38
38
  async function listOnce(appId, bucketId, opts) {
39
- const url = `/api/v1/storage/inner/app/${encodeURIComponent(appId)}/bucket/${encodeURIComponent(bucketId)}/list`;
39
+ const url = `/v1/storage/app/${encodeURIComponent(appId)}/bucket/${encodeURIComponent(bucketId)}/list`;
40
40
  const reqBody = {
41
41
  bucketID: bucketId,
42
42
  maxKeys: opts.limit,
@@ -94,7 +94,7 @@ function buildFilterExpr(opts) {
94
94
  /**
95
95
  * 列出文件:所有过滤下推到后端 FilterExpression,纯精确匹配,无 glob。
96
96
  *
97
- * 后端:POST /api/v1/storage/inner/app/{appId}/bucket/{bucketId}/list
97
+ * 后端:POST /v1/storage/app/{appId}/bucket/{bucketId}/list
98
98
  */
99
99
  async function listFiles(opts) {
100
100
  const bucketId = await (0, client_1.getDefaultBucketId)(opts.appId);
@@ -214,7 +214,7 @@ async function resolveByName(appId, input) {
214
214
  error: {
215
215
  code: "FILE_NOT_FOUND",
216
216
  message: `File '${input}' does not exist`,
217
- hint: "Run `miaoda file ls` to verify file_name.",
217
+ hint: "Run `miaoda file ls` to see available files.",
218
218
  },
219
219
  };
220
220
  }
@@ -225,7 +225,7 @@ async function resolveByName(appId, input) {
225
225
  error: {
226
226
  code: "AMBIGUOUS_FILE_NAME",
227
227
  message: `Multiple files match name '${input}' (${String(matches.length)} found)`,
228
- hint: `Use absolute /path instead. Run \`miaoda file ls --name ${input}\` to see candidates.`,
228
+ hint: `Use path instead. Run \`miaoda file ls --name ${input}\` to see candidates.`,
229
229
  },
230
230
  };
231
231
  }
@@ -234,12 +234,12 @@ async function resolveByName(appId, input) {
234
234
  // ── stat ──
235
235
  /**
236
236
  * 查看文件元数据。
237
- * 后端:GET /api/v1/storage/inner/app/{appId}/object/{bucketId}/{filePath}/head
237
+ * 后端:GET /v1/storage/app/{appId}/object/{bucketId}/{filePath}/head
238
238
  */
239
239
  async function statFile(opts) {
240
240
  const bucketId = await (0, client_1.getDefaultBucketId)(opts.appId);
241
241
  // 对齐 file-storage-skill Py 版:URL 顺序是 .../object/{bucket}/head/{path}
242
- const url = `/api/v1/storage/inner/app/${encodeURIComponent(opts.appId)}/object/${encodeURIComponent(bucketId)}/head/${encodePath(opts.filePath)}`;
242
+ const url = `/v1/storage/app/${encodeURIComponent(opts.appId)}/object/${encodeURIComponent(bucketId)}/head/${encodePath(opts.filePath)}`;
243
243
  const body = await (0, client_1.doGet)(url, {
244
244
  notFoundCode: "FILE_NOT_FOUND",
245
245
  notFoundMessage: `File '${opts.filePath}' does not exist`,
@@ -251,12 +251,12 @@ async function statFile(opts) {
251
251
  // ── 预签上传 URL ──
252
252
  async function preUpload(appId, req) {
253
253
  const bucketId = await (0, client_1.getDefaultBucketId)(appId);
254
- const url = `/api/v1/storage/inner/app/${encodeURIComponent(appId)}/bucket/${encodeURIComponent(bucketId)}/preUpload`;
254
+ const url = `/v1/storage/app/${encodeURIComponent(appId)}/bucket/${encodeURIComponent(bucketId)}/preUpload`;
255
255
  const body = await (0, client_1.doPost)(url, { bucketID: bucketId, appID: appId, ...req }, { errorContext: "pre-upload" });
256
256
  return extractEnvelope(body);
257
257
  }
258
258
  async function uploadCallback(appId, req) {
259
- const url = `/api/v1/storage/inner/app/${encodeURIComponent(appId)}/object/callback`;
259
+ const url = `/v1/storage/app/${encodeURIComponent(appId)}/object/callback`;
260
260
  const body = await (0, client_1.doPost)(url, req, { errorContext: "upload callback" });
261
261
  (0, client_1.ensureSuccess)(body);
262
262
  }
@@ -332,11 +332,11 @@ async function uploadFile(opts) {
332
332
  // ── 预签下载 URL ──
333
333
  /**
334
334
  * 获取预签下载 URL。
335
- * 后端:POST /api/v1/storage/inner/app/{appId}/object/sign/{bucketId}/{filePath}
335
+ * 后端:POST /v1/storage/app/{appId}/object/sign/{bucketId}/{filePath}
336
336
  */
337
337
  async function signDownload(opts) {
338
338
  const bucketId = await (0, client_1.getDefaultBucketId)(opts.appId);
339
- const url = `/api/v1/storage/inner/app/${encodeURIComponent(opts.appId)}/object/sign/${encodeURIComponent(bucketId)}/${encodePath(opts.filePath)}`;
339
+ const url = `/v1/storage/app/${encodeURIComponent(opts.appId)}/object/sign/${encodeURIComponent(bucketId)}/${encodePath(opts.filePath)}`;
340
340
  const reqBody = {
341
341
  bucketID: bucketId,
342
342
  filePath: toApiPath(opts.filePath),
@@ -381,11 +381,11 @@ async function downloadFile(opts) {
381
381
  // ── 批量删除(best-effort) ──
382
382
  /**
383
383
  * 批量删除文件。
384
- * 后端:DELETE /api/v1/storage/inner/app/{appId}/bucket/{bucketId}/delete
384
+ * 后端:DELETE /v1/storage/app/{appId}/bucket/{bucketId}/delete
385
385
  */
386
386
  async function deleteFiles(opts) {
387
387
  const bucketId = await (0, client_1.getDefaultBucketId)(opts.appId);
388
- const url = `/api/v1/storage/inner/app/${encodeURIComponent(opts.appId)}/bucket/${encodeURIComponent(bucketId)}/delete`;
388
+ const url = `/v1/storage/app/${encodeURIComponent(opts.appId)}/bucket/${encodeURIComponent(bucketId)}/delete`;
389
389
  const reqBody = {
390
390
  bucketID: bucketId,
391
391
  filePaths: opts.filePaths.map(toApiPath),
@@ -15,15 +15,16 @@ const bucketCache = new Map();
15
15
  * 获取默认 bucket(首次调用懒加载,进程内缓存)。
16
16
  *
17
17
  * 后端:GET /b/{appId}/get_published_v2
18
+ *
19
+ * 注意:这个接口属于运行端 innerapi(不是 admin 管理端),必须用
20
+ * getRuntimeHttpClient();其余 /v1/storage/app/... 六条 admin 接口走 admin client。
18
21
  */
19
22
  async function getDefaultBucketId(appId) {
20
23
  const cached = bucketCache.get(appId);
21
24
  if (cached)
22
25
  return cached;
23
26
  const url = `/b/${encodeURIComponent(appId)}/get_published_v2`;
24
- const body = await doGet(url, {
25
- errorContext: `fetch default bucket for app '${appId}'`,
26
- });
27
+ const body = await doGet(url, { errorContext: `fetch default bucket for app '${appId}'` }, (0, http_1.getRuntimeHttpClient)());
27
28
  ensureSuccess(body);
28
29
  const bucketId = body.data?.app_runtime_extra?.bucket?.default_bucket_id;
29
30
  if (!bucketId) {
@@ -123,9 +124,12 @@ async function mapHttpError(err, opts) {
123
124
  }
124
125
  throw err;
125
126
  }
126
- /** 包一层 client.get + HttpError 统一映射,成功时直接返回 body 的 json。 */
127
- async function doGet(url, opts = {}) {
128
- const client = (0, http_1.getHttpClient)();
127
+ /**
128
+ * 包一层 client.get + HttpError 统一映射,成功时直接返回 body 的 json。
129
+ * 默认走 admin innerapi 客户端;个别接口(如 get_published_v2)属于运行端,
130
+ * 通过第三个参数显式传入 getRuntimeHttpClient() 切换。
131
+ */
132
+ async function doGet(url, opts = {}, client = (0, http_1.getHttpClient)()) {
129
133
  try {
130
134
  const response = await client.get(url);
131
135
  return (await response.json());
@@ -135,9 +139,8 @@ async function doGet(url, opts = {}) {
135
139
  throw err; // 不可达,mapHttpError 必定 throw
136
140
  }
137
141
  }
138
- /** 包一层 client.post + HttpError 统一映射。 */
139
- async function doPost(url, body, opts = {}) {
140
- const client = (0, http_1.getHttpClient)();
142
+ /** 包一层 client.post + HttpError 统一映射。默认 admin innerapi,可显式切 runtime。 */
143
+ async function doPost(url, body, opts = {}, client = (0, http_1.getHttpClient)()) {
141
144
  try {
142
145
  const response = await client.post(url, body);
143
146
  return (await response.json());
@@ -148,8 +151,7 @@ async function doPost(url, body, opts = {}) {
148
151
  }
149
152
  }
150
153
  /** 包一层 client.request + HttpError 统一映射(DELETE 带 body 的场景)。 */
151
- async function doRequest(cfg, opts = {}) {
152
- const client = (0, http_1.getHttpClient)();
154
+ async function doRequest(cfg, opts = {}, client = (0, http_1.getHttpClient)()) {
153
155
  try {
154
156
  const response = await client.request(cfg);
155
157
  return (await response.json());
@@ -22,7 +22,7 @@ const node_fs_1 = __importDefault(require("node:fs"));
22
22
  const node_path_1 = __importDefault(require("node:path"));
23
23
  // ── Plugin Version API ──
24
24
  async function getPluginVersions(keys, latestOnly = true) {
25
- const client = (0, http_1.getHttpClient)();
25
+ const client = (0, http_1.getRuntimeHttpClient)();
26
26
  const response = await client.post(`/api/v1/studio/innerapi/plugins/-/versions/batch_get?keys=${keys.join(",")}&latest_only=${String(latestOnly)}`);
27
27
  if (!response.ok) {
28
28
  throw new error_1.HttpError(response.status, response.url, `Failed to get plugin versions: ${String(response.status)} ${response.statusText}`);
@@ -58,7 +58,7 @@ function parsePluginKey(key) {
58
58
  return { scope: match[1], name: match[2] };
59
59
  }
60
60
  async function downloadFromInner(pluginKey, version) {
61
- const client = (0, http_1.getHttpClient)();
61
+ const client = (0, http_1.getRuntimeHttpClient)();
62
62
  const { scope, name } = parsePluginKey(pluginKey);
63
63
  const url = `/api/v1/studio/innerapi/plugins/${scope}/${name}/versions/${version}/package`;
64
64
  const response = await client.get(url);
@@ -203,7 +203,7 @@ async function reportEvents(events) {
203
203
  if (events.length === 0)
204
204
  return true;
205
205
  try {
206
- const client = (0, http_1.getHttpClient)();
206
+ const client = (0, http_1.getRuntimeHttpClient)();
207
207
  const response = await client.post("/api/v1/studio/innerapi/resource_events", { events });
208
208
  if (!response.ok) {
209
209
  (0, logger_1.log)("telemetry", `Failed to report events: ${String(response.status)} ${response.statusText}`);
@@ -15,7 +15,7 @@ function registerDbCommands(program) {
15
15
  .description("执行任意 SQL(SELECT / DML / DDL / TCL / EXPLAIN);query 省略时读 stdin")
16
16
  .argument("[query]", "要执行的 SQL 语句;省略时从 stdin 读取")
17
17
  .addOption((0, shared_1.appIdOption)())
18
- .option("--env <env>", "目标环境(P0 未启用多环境)")
18
+ .option("--env <env>", "目标环境(main / dev);不传由后端按多环境状态兜底")
19
19
  .action(async (query, opts) => {
20
20
  await (0, index_1.handleDbSql)(query, opts);
21
21
  });
@@ -28,8 +28,9 @@ function registerDbCommands(program) {
28
28
  });
29
29
  schemaCmd
30
30
  .command("list")
31
- .description("列出应用所有表(rows / size / columns / updated_at)")
31
+ .description("列出应用所有表(estimated_row_count / size / columns)")
32
32
  .addOption((0, shared_1.appIdOption)())
33
+ .option("--env <env>", "目标环境(main / dev);不传由后端按多环境状态兜底")
33
34
  .action(async (opts) => {
34
35
  await (0, index_1.handleDbSchemaList)(opts);
35
36
  });
@@ -39,6 +40,7 @@ function registerDbCommands(program) {
39
40
  .argument("<table>", "表名")
40
41
  .addOption((0, shared_1.appIdOption)())
41
42
  .option("--ddl", "TTY 下强制输出完整 DDL 而非结构化概览")
43
+ .option("--env <env>", "目标环境(main / dev);不传由后端按多环境状态兜底")
42
44
  .action(async (table, opts) => {
43
45
  await (0, index_1.handleDbSchemaGet)(table, opts);
44
46
  });
@@ -3,6 +3,20 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.registerFileCommands = registerFileCommands;
4
4
  const index_1 = require("../../../cli/handlers/file/index");
5
5
  const shared_1 = require("../../../cli/commands/shared");
6
+ const error_1 = require("../../../utils/error");
7
+ /**
8
+ * commander option 校验器:把 --limit <n> 解析成正整数(≥1)。
9
+ * 默认值(如 "50")会先经过这里被规范化成 number。
10
+ * 非整数 / 负数 / 0 抛 AppError("ARGS_INVALID"),由 main.ts 的全局 catch
11
+ * 走 emitError,同时 process.exitCode 由 commander 自然为 1。
12
+ */
13
+ function parsePositiveInt(raw) {
14
+ const n = Number(raw);
15
+ if (!Number.isInteger(n) || n < 1) {
16
+ throw new error_1.AppError("ARGS_INVALID", `--limit must be a positive integer (got '${raw}')`);
17
+ }
18
+ return n;
19
+ }
6
20
  function registerFileCommands(program) {
7
21
  const fileCmd = program
8
22
  .command("file")
@@ -21,7 +35,7 @@ function registerFileCommands(program) {
21
35
  .option("--size-gt <size>", "大小大于,支持 B/KB/MB/GB")
22
36
  .option("--size-lt <size>", "大小小于")
23
37
  .option("--uploaded-since <time>", "上传时间晚于(ISO 8601)")
24
- .option("--limit <n>", "返回条数上限", "50")
38
+ .option("--limit <n>", "返回条数上限(正整数,默认 50)", parsePositiveInt, 50)
25
39
  .option("--cursor <token>", "分页游标")
26
40
  .option("--all", "自动翻页聚合全部结果")
27
41
  .action(async (query, opts) => {
@@ -7,7 +7,9 @@ exports.withHelp = withHelp;
7
7
  exports.failArgs = failArgs;
8
8
  const commander_1 = require("commander");
9
9
  const error_1 = require("../../utils/error");
10
- /** --app-id option,需要应用上下文的命令自行 .addOption(appIdOption()) */
10
+ /** --app-id option,需要应用上下文的命令自行 .addOption(appIdOption())。
11
+ * Commander 的 .env() 只接受单个变量名,第二个兜底 `app_id` 在 resolveAppId 里手动检查。
12
+ */
11
13
  function appIdOption() {
12
14
  return new commander_1.Option("--app-id <id>", "指定目标应用").env("MIAODA_APP_ID");
13
15
  }
@@ -17,9 +19,12 @@ function appIdOption() {
17
19
  function softRequiredOption(name, desc) {
18
20
  return new commander_1.Option(name, desc);
19
21
  }
20
- /** 解析 appId,CLI flag > env > 抛错 */
22
+ /**
23
+ * 解析 appId,优先级:CLI flag > MIAODA_APP_ID > app_id > 抛错。
24
+ * app_id 是部分外部沙箱环境注入应用 ID 的别名,作为兜底兼容(小写下划线形态)。
25
+ */
21
26
  function resolveAppId(opts) {
22
- const id = opts.appId ?? process.env.MIAODA_APP_ID;
27
+ const id = opts.appId ?? process.env.MIAODA_APP_ID ?? process.env.app_id;
23
28
  if (!id) {
24
29
  throw new error_1.AppError("APP_ID_MISSING", "未指定应用", {
25
30
  next_actions: [
@@ -41,7 +41,7 @@ const api = __importStar(require("../../../api/index"));
41
41
  const error_1 = require("../../../utils/error");
42
42
  const output_1 = require("../../../utils/output");
43
43
  const shared_1 = require("../../../cli/commands/shared");
44
- const shared_2 = require("../../../cli/handlers/shared");
44
+ const render_1 = require("../../../utils/render");
45
45
  // P0 规格(对齐技术方案关键决策 2)
46
46
  const MAX_SIZE_BYTES = 1 * 1024 * 1024; // 1 MB
47
47
  const MAX_ROWS = 5000;
@@ -82,15 +82,15 @@ async function handleDbDataImport(file, opts) {
82
82
  data: {
83
83
  file,
84
84
  table: result.tableName,
85
- rows: result.rows,
85
+ rows: result.recordCount,
86
86
  },
87
87
  });
88
88
  return;
89
89
  }
90
- const tty = (0, shared_2.isStdoutTty)();
90
+ const tty = (0, render_1.isStdoutTty)();
91
91
  (0, output_1.emit)(tty
92
- ? `✓ Imported ${file} → table '${result.tableName}' (${String(result.rows)} rows)`
93
- : `OK Imported ${file} -> table '${result.tableName}' (${String(result.rows)} rows)`);
92
+ ? `✓ Imported ${file} → table '${result.tableName}' (${String(result.recordCount)} rows)`
93
+ : `OK Imported ${file} -> table '${result.tableName}' (${String(result.recordCount)} rows)`);
94
94
  }
95
95
  async function handleDbDataExport(table, opts) {
96
96
  const appId = (0, shared_1.resolveAppId)(opts);
@@ -110,7 +110,8 @@ async function handleDbDataExport(table, opts) {
110
110
  throw new error_1.AppError("EXPORT_SIZE_EXCEEDED", `Export exceeds 1 MB limit (body is ${String(result.body.length)} bytes)`, { next_actions: [`Filter the table with "miaoda db sql" (e.g. WHERE/LIMIT) and export smaller subsets.`] });
111
111
  }
112
112
  await fs.writeFile(outputPath, result.body);
113
- const rows = countRows(result.body, format);
113
+ // 优先信任后端 X-Miaoda-Record-Count header;header 缺失时再用 body 行数兜底
114
+ const rows = result.recordCount ?? countRows(result.body, format);
114
115
  if ((0, output_1.isJsonMode)()) {
115
116
  (0, output_1.emit)({
116
117
  data: {
@@ -122,7 +123,7 @@ async function handleDbDataExport(table, opts) {
122
123
  });
123
124
  return;
124
125
  }
125
- const tty = (0, shared_2.isStdoutTty)();
126
+ const tty = (0, render_1.isStdoutTty)();
126
127
  (0, output_1.emit)(tty
127
128
  ? `✓ Exported ${table} → ${outputPath} (${String(rows)} rows)`
128
129
  : `OK Exported ${table} -> ${outputPath} (${String(rows)} rows)`);