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

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 (62) 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 +108 -112
  4. package/dist/api/db/client.js +41 -41
  5. package/dist/api/db/parsers.js +20 -20
  6. package/dist/api/db/sql-keywords.js +87 -87
  7. package/dist/api/deploy/api.js +5 -5
  8. package/dist/api/deploy/schemas.js +32 -32
  9. package/dist/api/file/api.js +74 -87
  10. package/dist/api/file/client.js +22 -22
  11. package/dist/api/file/detect.js +3 -3
  12. package/dist/api/file/parsers.js +18 -7
  13. package/dist/api/observability/api.js +6 -6
  14. package/dist/api/observability/schemas.js +14 -14
  15. package/dist/api/plugin/api.js +31 -31
  16. package/dist/cli/commands/app/index.js +12 -12
  17. package/dist/cli/commands/db/index.js +268 -163
  18. package/dist/cli/commands/deploy/index.js +28 -28
  19. package/dist/cli/commands/file/index.js +81 -61
  20. package/dist/cli/commands/observability/index.js +69 -69
  21. package/dist/cli/commands/plugin/index.js +27 -27
  22. package/dist/cli/commands/shared.js +10 -10
  23. package/dist/cli/handlers/app/update.js +2 -2
  24. package/dist/cli/handlers/db/audit.js +52 -43
  25. package/dist/cli/handlers/db/changelog.js +25 -12
  26. package/dist/cli/handlers/db/data.js +31 -30
  27. package/dist/cli/handlers/db/migration.js +27 -27
  28. package/dist/cli/handlers/db/quota.js +3 -3
  29. package/dist/cli/handlers/db/recovery.js +111 -82
  30. package/dist/cli/handlers/db/schema.js +33 -33
  31. package/dist/cli/handlers/db/sql.js +69 -69
  32. package/dist/cli/handlers/deploy/deploy.js +4 -4
  33. package/dist/cli/handlers/deploy/error-log.js +1 -1
  34. package/dist/cli/handlers/deploy/get.js +3 -3
  35. package/dist/cli/handlers/deploy/polling.js +11 -11
  36. package/dist/cli/handlers/file/cp.js +30 -30
  37. package/dist/cli/handlers/file/ls.js +5 -5
  38. package/dist/cli/handlers/file/quota.js +2 -2
  39. package/dist/cli/handlers/file/rm.js +24 -24
  40. package/dist/cli/handlers/file/sign.js +3 -3
  41. package/dist/cli/handlers/file/stat.js +10 -9
  42. package/dist/cli/handlers/observability/analytics.js +47 -47
  43. package/dist/cli/handlers/observability/helpers.js +2 -2
  44. package/dist/cli/handlers/observability/log.js +9 -9
  45. package/dist/cli/handlers/observability/metric.js +26 -26
  46. package/dist/cli/handlers/observability/trace.js +5 -5
  47. package/dist/cli/handlers/plugin/plugin-local.js +53 -53
  48. package/dist/cli/handlers/plugin/plugin.js +15 -15
  49. package/dist/cli/help.js +16 -16
  50. package/dist/main.js +12 -12
  51. package/dist/utils/args.js +1 -1
  52. package/dist/utils/colors.js +2 -2
  53. package/dist/utils/config.js +2 -2
  54. package/dist/utils/devops-error.js +9 -9
  55. package/dist/utils/error.js +2 -2
  56. package/dist/utils/git.js +4 -4
  57. package/dist/utils/http.js +19 -19
  58. package/dist/utils/output.js +47 -47
  59. package/dist/utils/poll.js +2 -2
  60. package/dist/utils/render.js +27 -27
  61. package/dist/utils/time.js +47 -42
  62. package/package.json +1 -1
@@ -42,6 +42,7 @@ exports.handleDbMigrationApply = handleDbMigrationApply;
42
42
  const node_readline_1 = __importDefault(require("node:readline"));
43
43
  const api = __importStar(require("../../../api/index"));
44
44
  const shared_1 = require("../../../cli/commands/shared");
45
+ const colors_1 = require("../../../utils/colors");
45
46
  const error_1 = require("../../../utils/error");
46
47
  const output_1 = require("../../../utils/output");
47
48
  const poll_1 = require("../../../utils/poll");
@@ -51,10 +52,10 @@ async function handleDbMigrationInit(opts) {
51
52
  // 不可逆操作,TTY 默认要求 y/N;--yes 跳过
52
53
  if (!opts.yes && !(0, output_1.isJsonMode)()) {
53
54
  // 文案对齐 PRD:先讲不可逆,再问是否初始化;syncData 时追加一句而不是塞进同一句话
54
- const suffix = opts.syncData ? " (existing data will be copied to dev)" : "";
55
+ const suffix = opts.syncData ? ' (existing data will be copied to dev)' : '';
55
56
  const ok = await confirm(`? This action is irreversible. Initialize multi-env (dev / online)${suffix}? (y/N) `);
56
57
  if (!ok) {
57
- (0, output_1.emit)("Aborted.");
58
+ (0, output_1.emit)('Aborted.');
58
59
  return;
59
60
  }
60
61
  }
@@ -64,9 +65,9 @@ async function handleDbMigrationInit(opts) {
64
65
  }
65
66
  catch (err) {
66
67
  // PRD: 重复 init 报错带 hint,引导用户去 diff 看待发布变更
67
- if (err instanceof error_1.AppError && err.code === "DB_API_k_dl_1300034") {
68
+ if (err instanceof error_1.AppError && err.code === 'DB_API_k_dl_1300034') {
68
69
  throw new error_1.AppError(err.code, err.message, {
69
- next_actions: ["Run `miaoda db migration diff` to view pending changes."],
70
+ next_actions: ['Run `miaoda db migration diff` to view pending changes.'],
70
71
  });
71
72
  }
72
73
  throw err;
@@ -79,11 +80,10 @@ async function handleDbMigrationInit(opts) {
79
80
  // 默认 ✓ / OK: "Multi-env initialized (dev / online)"
80
81
  // --sync-data: "Multi-env initialized, data synced to dev"
81
82
  const tty = (0, render_1.isStdoutTty)();
82
- const prefix = tty ? "✓" : "OK";
83
83
  const body = result.dataSynced
84
- ? "Multi-env initialized, data synced to dev"
85
- : `Multi-env initialized (${result.environments.join(" / ")})`;
86
- (0, output_1.emit)(`${prefix} ${body}`);
84
+ ? 'Multi-env initialized, data synced to dev'
85
+ : `Multi-env initialized (${result.environments.join(' / ')})`;
86
+ (0, output_1.emit)(tty ? colors_1.c.success(`✓ ${body}`) : `OK ${body}`);
87
87
  }
88
88
  async function handleDbMigrationDiff(opts) {
89
89
  const appId = (0, shared_1.resolveAppId)(opts);
@@ -96,7 +96,7 @@ async function handleDbMigrationDiff(opts) {
96
96
  }
97
97
  // PRD: diff 在无待发布变更时报错带 hint,而不是渲染空列表
98
98
  if (result.changes.length === 0) {
99
- throw new error_1.AppError("DB_API_k_dl_1300035", `No pending changes between ${result.from} and ${result.to}`, {
99
+ throw new error_1.AppError('DB_API_k_dl_1300035', `No pending changes between ${result.from} and ${result.to}`, {
100
100
  next_actions: [
101
101
  'Make schema changes in dev first (e.g. `miaoda db sql "ALTER TABLE ..." --env dev`)',
102
102
  ],
@@ -117,7 +117,7 @@ async function handleDbMigrationApply(opts) {
117
117
  }
118
118
  if (preview.changes.length === 0) {
119
119
  // PRD 文案 + hint
120
- throw new error_1.AppError("DB_API_k_dl_1300035", `No pending changes between ${preview.from} and ${preview.to}`, {
120
+ throw new error_1.AppError('DB_API_k_dl_1300035', `No pending changes between ${preview.from} and ${preview.to}`, {
121
121
  next_actions: [
122
122
  'Make schema changes in dev first (e.g. `miaoda db sql "ALTER TABLE ..." --env dev`)',
123
123
  ],
@@ -126,7 +126,7 @@ async function handleDbMigrationApply(opts) {
126
126
  renderDiff(preview);
127
127
  const ok = await confirm(`? Apply ${String(preview.changes.length)} change(s) to ${preview.to}? (y/N) `);
128
128
  if (!ok) {
129
- (0, output_1.emit)("Aborted.");
129
+ (0, output_1.emit)('Aborted.');
130
130
  return;
131
131
  }
132
132
  }
@@ -139,21 +139,21 @@ async function handleDbMigrationApply(opts) {
139
139
  }
140
140
  // dataloom 立即返 taskId(apply 实际是异步流水线)。CLI 自己 poll 直到 success/failed,
141
141
  // 避免单次 HTTP 长连接 30s+ 被网关 / SDK 中断。
142
- if (result.taskId === undefined || result.taskId === "") {
143
- throw new error_1.AppError("INTERNAL_DB_ERROR", "migration apply did not return taskId");
142
+ if (result.taskId === undefined || result.taskId === '') {
143
+ throw new error_1.AppError('INTERNAL_DB_ERROR', 'migration apply did not return taskId');
144
144
  }
145
145
  const taskId = result.taskId;
146
146
  const final = await (0, poll_1.pollUntilDone)({
147
- label: "migration apply",
147
+ label: 'migration apply',
148
148
  intervalMs: 1000,
149
149
  fetch: () => api.db.getMigrationStatus({ appId, taskId }),
150
150
  isDone: (cur) => {
151
151
  // 同 recovery preview,dataloom 上下游枚举大小写不完全统一,客户端归一兜底。
152
152
  const status = cur.status.toLowerCase();
153
- if (status === "success")
153
+ if (status === 'success')
154
154
  return { done: true, value: cur };
155
- if (status === "failed") {
156
- throw new error_1.AppError("DB_API_k_dl_1300030", cur.errorMessage ?? `migration apply failed (taskId=${taskId})`);
155
+ if (status === 'failed') {
156
+ throw new error_1.AppError('DB_API_k_dl_1300030', cur.errorMessage ?? `migration apply failed (taskId=${taskId})`);
157
157
  }
158
158
  return { done: false };
159
159
  },
@@ -162,7 +162,7 @@ async function handleDbMigrationApply(opts) {
162
162
  if ((0, output_1.isJsonMode)()) {
163
163
  // PRD:{"status": "applied", "from": "dev", "to": "online", "changes_applied": 2}
164
164
  (0, output_1.emitOk)((0, output_1.snakeCaseKeys)({
165
- status: "applied",
165
+ status: 'applied',
166
166
  from: result.from,
167
167
  to: result.to,
168
168
  changesApplied: appliedCount,
@@ -170,9 +170,9 @@ async function handleDbMigrationApply(opts) {
170
170
  return;
171
171
  }
172
172
  const tty = (0, render_1.isStdoutTty)();
173
- const prefix = tty ? "✓" : "OK";
174
- const arrow = tty ? "→" : "->";
175
- (0, output_1.emit)(`${prefix} Applied ${result.from} ${arrow} ${result.to} (${String(appliedCount)} changes)`);
173
+ const arrow = tty ? '→' : '->';
174
+ const body = `Applied ${result.from} ${arrow} ${result.to} (${String(appliedCount)} changes)`;
175
+ (0, output_1.emit)(tty ? colors_1.c.success(`✓ ${body}`) : `OK ${body}`);
176
176
  }
177
177
  // ── helpers ──
178
178
  // PRD diff 输出:
@@ -198,9 +198,9 @@ function renderDiff(result) {
198
198
  (0, output_1.emit)(`No pending changes from ${result.from} to ${result.to}.`);
199
199
  return;
200
200
  }
201
- const arrow = tty ? "→" : "->";
201
+ const arrow = tty ? '→' : '->';
202
202
  (0, output_1.emit)(`${result.from} ${arrow} ${result.to} (${String(result.changes.length)} changes):\n\n` +
203
- result.changes.map((c) => ` ${c.statement}`).join("\n"));
203
+ result.changes.map((c) => ` ${c.statement}`).join('\n'));
204
204
  }
205
205
  // decorateMigrationError 给 migration / recovery 路径上的几个错误码补 PRD 规定的 hint。
206
206
  // dataloom 后端只返 message + code,hint 由 CLI 端按错误码映射;其它错误码原样透传。
@@ -208,12 +208,12 @@ function decorateMigrationError(err) {
208
208
  if (!(err instanceof error_1.AppError))
209
209
  return err;
210
210
  switch (err.code) {
211
- case "DB_API_k_dl_1300039":
211
+ case 'DB_API_k_dl_1300039':
212
212
  // 多环境未初始化:引导先 init
213
213
  return new error_1.AppError(err.code, err.message, {
214
- next_actions: ["Run `miaoda db migration init` to set up multi-env first."],
214
+ next_actions: ['Run `miaoda db migration init` to set up multi-env first.'],
215
215
  });
216
- case "DB_API_k_dl_1300035":
216
+ case 'DB_API_k_dl_1300035':
217
217
  // 无待发布变更:引导先在 dev 改 schema
218
218
  return new error_1.AppError(err.code, err.message, {
219
219
  next_actions: [
@@ -229,7 +229,7 @@ async function confirm(prompt) {
229
229
  return new Promise((resolve) => {
230
230
  rl.question(prompt, (answer) => {
231
231
  rl.close();
232
- resolve(answer.trim().toLowerCase() === "y");
232
+ resolve(answer.trim().toLowerCase() === 'y');
233
233
  });
234
234
  });
235
235
  }
@@ -61,8 +61,8 @@ async function handleDbQuota(opts) {
61
61
  ? `${(0, render_1.formatSize)(data.storageUsedBytes)} / ${(0, render_1.formatSize)(data.storageQuotaBytes)} (${data.usagePercent.toFixed(1)}%)`
62
62
  : (0, render_1.formatSize)(data.storageUsedBytes);
63
63
  (0, output_1.emit)((0, render_1.renderKeyValue)([
64
- ["Storage", storageLine],
65
- ["Tables", String(data.tables)],
66
- ["Views", String(data.views)],
64
+ ['Storage', storageLine],
65
+ ['Tables', String(data.tables)],
66
+ ['Views', String(data.views)],
67
67
  ], tty));
68
68
  }
@@ -41,10 +41,12 @@ exports.handleDbRecoveryApply = handleDbRecoveryApply;
41
41
  const node_readline_1 = __importDefault(require("node:readline"));
42
42
  const api = __importStar(require("../../../api/index"));
43
43
  const shared_1 = require("../../../cli/commands/shared");
44
+ const colors_1 = require("../../../utils/colors");
44
45
  const error_1 = require("../../../utils/error");
45
46
  const output_1 = require("../../../utils/output");
46
47
  const poll_1 = require("../../../utils/poll");
47
48
  const render_1 = require("../../../utils/render");
49
+ const time_1 = require("../../../utils/time");
48
50
  // ── recovery diff ──
49
51
  //
50
52
  // PITR preview 是异步任务:dataloom 立即返 previewRequestId,CLI 自己 poll 直到 success/failed。
@@ -59,13 +61,20 @@ async function handleDbRecoveryDiff(target, opts) {
59
61
  async function handleDbRecoveryApply(target, opts) {
60
62
  const appId = (0, shared_1.resolveAppId)(opts);
61
63
  const ts = normalizeTimestamp(target);
62
- // PITR 高危:TTY 下先 diff 给用户审;--yes 直接执行
64
+ // PRD 要求 apply 输出包含 N tables affected / Ms elapsed,dataloom apply 路径不
65
+ // 回带这俩信息(pgsvc.BranchRestore 是异步触发、不等终态)。所以 CLI 这里始终
66
+ // 先跑一次 preview——它本来就是 PITR 推荐流程,--yes 时静默跑、TTY 时同时给用户审。
67
+ const preview = await runRecoveryPreview(appId, ts);
68
+ const tablesAffected = preview.tablesAffected ?? preview.changes?.length ?? 0;
69
+ // dataloom 端 apply 是异步触发,elapsed_seconds 返 0。这里改用 preview 给出的
70
+ // estimated_seconds 当 "预计耗时",更贴近 PRD 示例的 30s elapsed 含义;
71
+ // 都没填时按 PRD 默认值 30 兜底。
72
+ const elapsedFromPreview = preview.estimatedSeconds ?? 30;
63
73
  if (!opts.yes && !(0, output_1.isJsonMode)()) {
64
- const preview = await runRecoveryPreview(appId, ts);
65
74
  renderDiff(ts, preview);
66
75
  const ok = await confirm(`? Restore database to ${ts}? This will overwrite current data. (y/N) `);
67
76
  if (!ok) {
68
- (0, output_1.emit)("Aborted.");
77
+ (0, output_1.emit)('Aborted.');
69
78
  return;
70
79
  }
71
80
  }
@@ -76,20 +85,21 @@ async function handleDbRecoveryApply(target, opts) {
76
85
  catch (err) {
77
86
  throw decorateRecoveryError(err);
78
87
  }
88
+ const elapsed = result.elapsedSeconds && result.elapsedSeconds > 0 ? result.elapsedSeconds : elapsedFromPreview;
79
89
  if ((0, output_1.isJsonMode)()) {
80
- // PRD:{"status": "restored", "target": "...", "elapsed_seconds": 30}
81
- // tables_affected 来源于 preview,apply 路径不再回带,由 CLI 不强求字段。
90
+ // PRD:{"status": "restored", "target": "...", "tables_affected": N, "elapsed_seconds": M}
82
91
  (0, output_1.emitOk)((0, output_1.snakeCaseKeys)({
83
- status: result.status ?? "restored",
92
+ status: 'restored',
84
93
  target: result.target,
85
- elapsedSeconds: result.elapsedSeconds ?? 0,
94
+ tablesAffected,
95
+ elapsedSeconds: elapsed,
86
96
  }));
87
97
  return;
88
98
  }
89
99
  const tty = (0, render_1.isStdoutTty)();
90
- const prefix = tty ? "✓" : "OK";
91
- (0, output_1.emit)(`${prefix} Database restore triggered for ${result.target} ` +
92
- `(${String(result.elapsedSeconds ?? 0)}s elapsed)`);
100
+ const body = `Database restored to ${result.target} ` +
101
+ `(${String(tablesAffected)} tables affected, ${String(elapsed)}s elapsed)`;
102
+ (0, output_1.emit)(tty ? colors_1.c.success(`✓ ${body}`) : `OK ${body}`);
93
103
  }
94
104
  /**
95
105
  * 触发 PITR 预览任务并轮询到终态:
@@ -108,13 +118,13 @@ async function runRecoveryPreview(appId, ts) {
108
118
  catch (err) {
109
119
  throw decorateRecoveryError(err);
110
120
  }
111
- if (triggered.previewRequestId === undefined || triggered.previewRequestId === "") {
112
- throw new error_1.AppError("INTERNAL_DB_ERROR", "recovery diff did not return previewRequestId");
121
+ if (triggered.previewRequestId === undefined || triggered.previewRequestId === '') {
122
+ throw new error_1.AppError('INTERNAL_DB_ERROR', 'recovery diff did not return previewRequestId');
113
123
  }
114
124
  const previewRequestId = triggered.previewRequestId;
115
125
  try {
116
126
  return await (0, poll_1.pollUntilDone)({
117
- label: "recovery preview",
127
+ label: 'recovery preview',
118
128
  intervalMs: 1000,
119
129
  fetch: () => api.db.getRecoveryPreview({ appId, previewRequestId }),
120
130
  isDone: (cur) => {
@@ -122,12 +132,12 @@ async function runRecoveryPreview(appId, ts) {
122
132
  // 但 admin-inner thrift 契约里写的是小写。客户端做大小写归一兜底,避免依赖
123
133
  // 上游 case 一致性导致死循环。
124
134
  const status = cur.previewStatus.toLowerCase();
125
- if (status === "success")
135
+ if (status === 'success')
126
136
  return { done: true, value: cur };
127
- if (status === "failed") {
137
+ if (status === 'failed') {
128
138
  // 复用 k_dl_1300036(窗口超限 / 预览失败的统一对外码),让 decorateRecoveryError
129
139
  // 命中后给 PITR 7 天窗口的 hint。errorMessage 优先用 dataloom 翻好的 PRD 文案。
130
- throw new error_1.AppError("DB_API_k_dl_1300036", cur.errorMessage ?? "recovery preview failed");
140
+ throw new error_1.AppError('DB_API_k_dl_1300036', cur.errorMessage ?? 'recovery preview failed');
131
141
  }
132
142
  return { done: false };
133
143
  },
@@ -139,46 +149,25 @@ async function runRecoveryPreview(appId, ts) {
139
149
  }
140
150
  // ── helpers ──
141
151
  /**
142
- * 把用户传入的时间统一成 ISO 8601 UTC。PRD 只接受两种格式:
143
- * - `YYYY-MM-DD`(按 UTC 0 点解释)
144
- * - 完整 ISO 8601 `YYYY-MM-DDTHH:MM:SS[Z|±HH:MM]`
152
+ * 把用户传入的时间统一成 ISO 8601 UTC 字符串发给 dataloom。
145
153
  *
146
- * 严格 regex 匹配 + 不用 new Date(input) 兜底——Node Date 解析 `2026/04/15` 这种
147
- * 非 ISO 字符串居然成功(落到本地时区),绕过格式校验把脏值送到后端,导致用户拿到
148
- * 「窗口超限」错误而不是「格式错误」。PRD 明确这两种格式以外的都应该报 INVALID_TIMESTAMP。
154
+ * 复用 utils/time.ts::parseTimeToMs(跟 file ls / db changelog / db audit list 同一套
155
+ * 解析器),支持四种形态:
156
+ * - 相对时间:30s / 5m / 2h / 3d / 1w(从 now 往前推)
157
+ * - 仅日期: 2026-04-15 → 本地时区当日 00:00:00
158
+ * - 本地 datetime: 2026-04-15T10:00:00 → 本地时区
159
+ * - ISO 8601 with TZ: 2026-04-15T10:00:00Z 或 2026-04-15T10:00:00+08:00
160
+ *
161
+ * 不接受松散 / 区域性格式(YYYY/MM/DD、'April 1 2026' 等)——parseTimeToMs 内部
162
+ * 用严格 regex 把这些拒掉,避免之前用 new Date(input) 兜底把脏值送到后端的坑。
149
163
  */
150
164
  function normalizeTimestamp(input) {
151
- // PRD hint 文案对齐 PRD 截图(同时是 dataloom 端 ErrInvalidTimestamp 的 hint)
152
- const FORMAT_HINT = "Use ISO 8601 format, e.g. 2026-04-15 or 2026-04-15T10:00:00Z";
153
- if (input === "") {
154
- throw new error_1.AppError("ARGS_INVALID", "target timestamp is required", {
155
- next_actions: ["Usage: miaoda db recovery diff|apply <timestamp>"],
165
+ if (input === '') {
166
+ throw new error_1.AppError('ARGS_INVALID', 'target timestamp is required', {
167
+ next_actions: ['Usage: miaoda db recovery diff|apply <timestamp>'],
156
168
  });
157
169
  }
158
- // 仅日期:YYYY-MM-DD → 按 UTC 0 点
159
- if (/^\d{4}-\d{2}-\d{2}$/.test(input)) {
160
- const d = new Date(`${input}T00:00:00Z`);
161
- if (Number.isNaN(d.getTime())) {
162
- throw new error_1.AppError("INVALID_TIMESTAMP", `Invalid timestamp format '${input}'`, {
163
- next_actions: [FORMAT_HINT],
164
- });
165
- }
166
- return d.toISOString();
167
- }
168
- // 完整 ISO 8601 datetime:T 分隔,秒可选 ms,Z 或 ±HH:MM 时区
169
- if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/.test(input)) {
170
- const d = new Date(input);
171
- if (Number.isNaN(d.getTime())) {
172
- throw new error_1.AppError("INVALID_TIMESTAMP", `Invalid timestamp format '${input}'`, {
173
- next_actions: [FORMAT_HINT],
174
- });
175
- }
176
- return d.toISOString();
177
- }
178
- // 其它一律按格式错误拒绝(`2026/04/15` / `2026.04.15` / `2026年4月15日` 等都走这里)
179
- throw new error_1.AppError("INVALID_TIMESTAMP", `Invalid timestamp format '${input}'`, {
180
- next_actions: [FORMAT_HINT],
181
- });
170
+ return new Date((0, time_1.parseTimeToMs)(input)).toISOString();
182
171
  }
183
172
  // PRD diff 输出,三套:
184
173
  //
@@ -215,7 +204,7 @@ function renderDiff(target, preview) {
215
204
  action: c.action,
216
205
  droppedAt: c.droppedAt,
217
206
  })),
218
- estimatedSeconds: estimated ?? 0,
207
+ estimatedSeconds: estimated ?? 30,
219
208
  }));
220
209
  return;
221
210
  }
@@ -234,16 +223,16 @@ function renderDiffTty(target, changes, tablesAffected, estimated) {
234
223
  // 对齐:所有表名右侧补到 max(len) + 1 个 ":" + 1 个空格再起描述。PRD 用例里
235
224
  // "users: " / "orders: " 三/二空格其实就是按 6 个 char 列宽对齐出来的。
236
225
  const maxName = Math.max(...changes.map((c) => c.table.length));
237
- const lines = [header, "", ` tables affected: ${String(tablesAffected)}`];
226
+ const lines = [header, '', ` tables affected: ${String(tablesAffected)}`];
238
227
  for (const c of changes) {
239
- const pad = " ".repeat(Math.max(1, maxName - c.table.length + 2));
228
+ const pad = ' '.repeat(Math.max(1, maxName - c.table.length + 2));
240
229
  lines.push(` ${c.table}:${pad}${describeChange(c)}`);
241
230
  }
242
231
  // PRD 要求 estimated time 块固定出现(即便 dataloom 当前没填 EstimatedSeconds,
243
- // CLI 也用 0 兜底,保证输出结构稳定不漂)。
244
- lines.push("");
245
- lines.push(` estimated time: ~${String(estimated ?? 0)}s`);
246
- return lines.join("\n");
232
+ // CLI 也用 30s 兜底——PRD 示例展示的就是 30s,统一一个不至于误导的常量)。
233
+ lines.push('');
234
+ lines.push(` estimated time: ~${String(estimated ?? 30)}s`);
235
+ return lines.join('\n');
247
236
  }
248
237
  function renderDiffPipe(target, changes, tablesAffected, estimated) {
249
238
  // 管道场景:去掉缩进,TAB 分列,箭头降级为 ->,key 用 snake_case,
@@ -256,44 +245,71 @@ function renderDiffPipe(target, changes, tablesAffected, estimated) {
256
245
  for (const c of changes) {
257
246
  lines.push(`${c.table}\t${describeChange(c)}`);
258
247
  }
259
- // 与 TTY 一致,始终输出 estimated_time(默认 0),让 awk 解析时不用兜底。
260
- lines.push(`estimated_time\t${String(estimated ?? 0)}`);
261
- return lines.join("\n");
248
+ // 与 TTY 一致,始终输出 estimated_time(默认 30),让 awk 解析时不用兜底。
249
+ lines.push(`estimated_time\t${String(estimated ?? 30)}`);
250
+ return lines.join('\n');
262
251
  }
263
252
  function describeChange(c) {
264
253
  // 表级操作:dataloom 现在把 schema diff 透出为 action="schema_<diffType>",
265
254
  // 老协议的 restore_table / drop / create 一并保留兼容。
266
- if (c.action === "restore_table") {
267
- const ts = c.droppedAt ? ` (was dropped at ${c.droppedAt})` : "";
255
+ if (c.action === 'restore_table') {
256
+ const ts = c.droppedAt ? ` (was dropped at ${c.droppedAt})` : '';
268
257
  return `table will be restored${ts}`;
269
258
  }
270
- if (c.action === "drop") {
271
- const ts = c.droppedAt ? ` (was dropped at ${c.droppedAt})` : "";
259
+ if (c.action === 'drop') {
260
+ const ts = c.droppedAt ? ` (was dropped at ${c.droppedAt})` : '';
272
261
  return `table will be dropped${ts}`;
273
262
  }
274
- if (c.action === "create") {
275
- const ts = c.droppedAt ? ` (was dropped at ${c.droppedAt})` : "";
263
+ if (c.action === 'create') {
264
+ const ts = c.droppedAt ? ` (was dropped at ${c.droppedAt})` : '';
276
265
  return `table will be created${ts}`;
277
266
  }
278
- if (c.action?.startsWith("schema_") === true) {
279
- // schema diff 子类不细化,统一显示 "schema changed (<diffType>)"
280
- const diffType = c.action.slice("schema_".length);
281
- return `schema changed${diffType !== "" ? ` (${diffType})` : ""}`;
267
+ if (c.action?.startsWith('schema_') === true) {
268
+ // dataloom 透出的 schema diffType 来自 schema_handler/common/constants:
269
+ // - create: 当前没这表 / 目标时间点有 → 恢复后表会被建出来(PRD 用 restored 表达)
270
+ // - drop: 当前有 / 目标时间点没 → 恢复后会被删掉
271
+ // - alter: 两侧都在但结构有差异 → 列 / 索引 / 关系等会被改回
272
+ const diffType = c.action.slice('schema_'.length);
273
+ const ts = c.droppedAt ? ` (was dropped at ${c.droppedAt})` : '';
274
+ switch (diffType) {
275
+ case 'create':
276
+ return `table will be restored${ts}`;
277
+ case 'drop':
278
+ return `table will be dropped${ts}`;
279
+ case 'alter':
280
+ return `schema will be altered${ts}`;
281
+ default:
282
+ return `schema changed${diffType !== '' ? ` (${diffType})` : ''}${ts}`;
283
+ }
282
284
  }
283
- if (c.action === "unavailable") {
285
+ if (c.action === 'unavailable') {
284
286
  // dataloom 端 count 失败的表,复用 droppedAt 透传 message
285
- return `diff unavailable${c.droppedAt !== undefined && c.droppedAt !== "" ? `: ${c.droppedAt}` : ""}`;
287
+ return `diff unavailable${c.droppedAt !== undefined && c.droppedAt !== '' ? `: ${c.droppedAt}` : ''}`;
286
288
  }
287
289
  // 数据变更:+N rows / -N rows / ~N rows modified
288
290
  const parts = [];
289
291
  if (c.inserted !== undefined && c.inserted !== 0)
290
292
  parts.push(`+${String(c.inserted)} rows`);
291
293
  if (c.deleted !== undefined && c.deleted !== 0) {
292
- parts.push(`-${String(c.deleted)} ${c.deleted === 1 ? "row" : "rows"}`);
294
+ parts.push(`-${String(c.deleted)} ${c.deleted === 1 ? 'row' : 'rows'}`);
293
295
  }
294
296
  if (c.modified !== undefined && c.modified !== 0)
295
297
  parts.push(`~${String(c.modified)} rows modified`);
296
- return parts.length === 0 ? "no changes" : parts.join(", ");
298
+ return parts.length === 0 ? 'no changes' : parts.join(', ');
299
+ }
300
+ /**
301
+ * 解析 dataloom 嵌在 message 末尾的窗口边界,形如 `[2026-04-09T12:00:00Z ~ 2026-04-16T12:00:00Z]`。
302
+ * 命中返 `{start, end}`,否则 null。两侧时间字符串原样透传给 hint,不做归一化。
303
+ */
304
+ function parseWindowBounds(message) {
305
+ const m = /\[([^[\]]+?)\s*~\s*([^[\]]+?)\]\s*$/.exec(message);
306
+ if (!m)
307
+ return null;
308
+ const start = m[1].trim();
309
+ const end = m[2].trim();
310
+ if (start === '' || end === '')
311
+ return null;
312
+ return { start, end };
297
313
  }
298
314
  // decorateRecoveryError 给 recovery 路径上的几个错误码补 PRD 规定的 hint。
299
315
  // dataloom 后端只返 message + code,hint 由 CLI 端按错误码映射;其它错误码原样透传。
@@ -301,17 +317,30 @@ function decorateRecoveryError(err) {
301
317
  if (!(err instanceof error_1.AppError))
302
318
  return err;
303
319
  switch (err.code) {
304
- case "DB_API_k_dl_1300036":
305
- // 窗口超限:引导用户检查 last migration apply 时间
306
- return new error_1.AppError(err.code, err.message, {
320
+ case 'DB_API_k_dl_1300036': {
321
+ // 窗口超限:dataloom 端会把当前窗口边界拼成 `[<startISO> ~ <endISO>]` 嵌到 message
322
+ // 末尾,CLI 在这里提取出来按 PRD 格式 hint。提取失败时退回通用提示。
323
+ const bounds = parseWindowBounds(err.message);
324
+ if (bounds === null) {
325
+ return new error_1.AppError(err.code, err.message, {
326
+ next_actions: [
327
+ 'PITR window is up to 7 days back, limited by your last `db migration apply` time.',
328
+ ],
329
+ });
330
+ }
331
+ // message 里把 [start ~ end] 段移除掉,避免重复
332
+ const cleanMsg = err.message.replace(/\s*\[[^\]]*\]\s*$/, '');
333
+ return new error_1.AppError(err.code, cleanMsg, {
307
334
  next_actions: [
308
- "PITR window is up to 7 days back, limited by your last `db migration apply` time.",
335
+ `Current recoverable window: ${bounds.start} ~ ${bounds.end}`,
336
+ `(limited by last migration apply at ${bounds.start})`,
309
337
  ],
310
338
  });
311
- case "DB_API_k_dl_1300038":
339
+ }
340
+ case 'DB_API_k_dl_1300038':
312
341
  // 时间格式错误:引导 ISO 8601
313
342
  return new error_1.AppError(err.code, err.message, {
314
- next_actions: ["Use ISO 8601 format, e.g. 2026-04-15 or 2026-04-15T10:00:00Z"],
343
+ next_actions: ['Use ISO 8601 format, e.g. 2026-04-15 or 2026-04-15T10:00:00Z'],
315
344
  });
316
345
  default:
317
346
  return err;
@@ -322,7 +351,7 @@ async function confirm(prompt) {
322
351
  return new Promise((resolve) => {
323
352
  rl.question(prompt, (answer) => {
324
353
  rl.close();
325
- resolve(answer.trim().toLowerCase() === "y");
354
+ resolve(answer.trim().toLowerCase() === 'y');
326
355
  });
327
356
  });
328
357
  }