@collectui/cli 0.2.19 → 0.2.20

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.
package/README.md CHANGED
@@ -47,7 +47,7 @@ collectui login --token dpat_... --json # 或显式传入
47
47
  ## 看账户与库
48
48
 
49
49
  ```bash
50
- collectui whoami # 账户、按站权限、绑定 key、可下仓库、订单
50
+ collectui whoami # 我是谁:账户名 + uid(权益清单看 libs;--json 仍是全量聚合)
51
51
  collectui libs # 全库目录 + 你是否拥有 + CLI/MCP key 状态
52
52
  collectui libs --json # Agent 用
53
53
  ```
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@collectui/cli",
3
- "version": "0.2.19",
4
- "description": "One CLI for every shadcn library on CollectUI Dash \u2014 login once, configure registries & MCP, scaffold agent-ready projects.",
3
+ "version": "0.2.20",
4
+ "description": "One CLI for every shadcn library on CollectUI Dash — login once, configure registries & MCP, scaffold agent-ready projects.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
package/src/catalog.mjs CHANGED
@@ -421,6 +421,7 @@ export async function fetchCatalog({ reporter } = {}) {
421
421
  timeout: 8_000,
422
422
  retries: 1,
423
423
  reporter,
424
+ spinner: "Loading the library catalog from Dash…",
424
425
  }).catch((error) => {
425
426
  reporter?.info?.(`Catalog endpoint unavailable (${error.message}); using built-in snapshot.`);
426
427
  return null;
package/src/cli.mjs CHANGED
@@ -37,7 +37,7 @@ Usage:
37
37
  Commands:
38
38
  login Authorize CollectUI CLI in your browser (OAuth-style)
39
39
  logout Remove the saved PAT
40
- whoami, me Show account, libraries, bound keys and repos
40
+ whoami, me Show who you are logged in as (account name + uid)
41
41
  libs List every library, ownership and key status
42
42
  init [dir] Scaffold a fresh shadcn project and configure libraries (no dir: OS temp dir)
43
43
  configure [dir] Configure an existing shadcn project
@@ -99,7 +99,7 @@ const COMMANDS = {
99
99
  login: { run: loginCmd, aliases: [] },
100
100
  logout: { run: logoutCmd, aliases: [] },
101
101
  whoami: { run: whoamiCmd, aliases: ["me"] },
102
- libs: { run: libsCmd, aliases: ["list"] },
102
+ libs: { run: libsCmd, aliases: ["list"], parallel: true },
103
103
  init: { run: initCmd, aliases: ["new"] },
104
104
  configure: { run: configureCmd, aliases: ["config", "setup"] },
105
105
  add: { run: addCmd, aliases: ["install"] },
@@ -118,8 +118,12 @@ function findCommand(name) {
118
118
  return null;
119
119
  }
120
120
 
121
- /** 纯本地/纯账号命令不拉动态目录(省一次网络等待)。 */
122
- const CATALOG_SKIP = new Set(["login", "logout", "whoami", "update"]);
121
+ /**
122
+ * 纯本地/纯账号命令不拉动态目录(省一次网络等待):dash 子命令全是 Dash MCP 调用、
123
+ * skill 只落一个文件,都读不到目录。libs 标了 parallel——入口不等目录,命令里把
124
+ * 目录与账号两请求同 tick 并行发出(谁慢等谁,省掉串行那一趟)。
125
+ */
126
+ const CATALOG_SKIP = new Set(["login", "logout", "whoami", "update", "dash", "skill"]);
123
127
 
124
128
  function printHelp() {
125
129
  process.stdout.write(HELP);
@@ -169,20 +173,24 @@ async function main() {
169
173
  if (token) reporter.addSecrets([token]);
170
174
 
171
175
  showBanner(reporter); // 开机画面:任何子命令(headless/--version/help 已在前面分流)
172
- // 动态目录(Dash GET /api/libs):新上库自动包含、停用站自动剔除;失败降级
173
- // 内置快照(目录可用性优先)——与更新检查互不影响
174
- if (!CATALOG_SKIP.has(name)) await ensureCatalog({ reporter });
175
- // 更新检查:与命令并行即时异步查一次 npm(TTY 才查),有新版打一行提醒;
176
- // 手动 update 命令自身不触发(避免与前台安装并发写全局目录)
176
+ // 更新检查最先出发:与目录/账号请求并行,命令收尾时多半已查完(少等收尾那 1 秒)。
177
+ // TTY 才查,有新版打一行提醒;手动 update 命令自身不触发(避免与前台安装并发写全局目录)
177
178
  const updateNotice =
178
179
  name !== "update" && name !== "upgrade" ? startBackgroundUpdate(reporter) : null;
180
+ // 动态目录(Dash GET /api/libs):新上库自动包含、停用站自动剔除;失败降级
181
+ // 内置快照(目录可用性优先)——与更新检查互不影响
182
+ if (!CATALOG_SKIP.has(name) && !command.parallel) await ensureCatalog({ reporter });
179
183
  const race = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(r, ms))]);
180
184
  const settleUpdate = updateNotice
181
185
  ? () => race(updateNotice.done, 1_000).catch(() => {})
182
186
  : () => Promise.resolve();
183
187
 
184
- await command.run(flags, rest, reporter);
185
- await settleUpdate();
188
+ try {
189
+ await command.run(flags, rest, reporter);
190
+ await settleUpdate();
191
+ } finally {
192
+ reporter.settleLoading(); // 异常退出也不把 spinner 行 / 藏起的光标留在终端
193
+ }
186
194
  }
187
195
 
188
196
  /** 命令完成后 flush stdout 并退出:一次性进程不留后台尾巴(callback server 的
@@ -9,7 +9,7 @@ import {
9
9
  } from "../catalog.mjs";
10
10
  import { resolveToken } from "../config.mjs";
11
11
  import { authError, usageError } from "../errors.mjs";
12
- import { fetchMe } from "../dash.mjs";
12
+ import { fetchAccount, fetchMe } from "../dash.mjs";
13
13
 
14
14
  export function requireToken(flags, reporter) {
15
15
  const token = resolveToken(flags);
@@ -36,6 +36,14 @@ export async function loadMe(flags, reporter, { required = true } = {}) {
36
36
  return me;
37
37
  }
38
38
 
39
+ /** whoami 用:只要账户本体(轻量端点,不触发 /api/me 的全量聚合)。 */
40
+ export async function loadAccount(flags, reporter) {
41
+ const token = resolveToken(flags);
42
+ if (!token) return requireToken(flags, reporter);
43
+ reporter?.addSecrets([token]);
44
+ return fetchAccount(token, { reporter });
45
+ }
46
+
39
47
  export function ownedSlugs(me) {
40
48
  return new Set(ownedLibs(me).map((lib) => lib.site));
41
49
  }
@@ -93,6 +93,7 @@ export async function doctorCmd(flags, rest, reporter) {
93
93
  headers: probe.headers,
94
94
  reporter,
95
95
  label: `registry probe ${lib.site}`,
96
+ spinner: `Probing the ${lib.site} registry…`,
96
97
  timeout: 20_000,
97
98
  retries: 1,
98
99
  });
@@ -1,21 +1,30 @@
1
1
  import { activeCatalog, ownedLibs, resolveLibKeys, retiredSlugs } from "../catalog.mjs";
2
- import { formatTable, startSpin } from "../report.mjs";
2
+ import { ensureCatalog } from "../catalog.mjs";
3
+ import { formatTable } from "../report.mjs";
3
4
  import { loadMe } from "./common.mjs";
4
5
 
5
6
  /**
6
7
  * cui libs 精简三列:SITE + CLI KEY + MCP KEY(MCP 值区分专属 bound / 通用 generic)
7
8
  * cui libs --verbose 完整表格(registries/MCP server 名等内部细节)
8
- * 未拥有的行两列均为 "-";加载态为行内覆写 spinner(不闪)。
9
+ * 未拥有的行两列均为 "-";加载态为行内覆写 spinner(不闪),品牌一出就转。
9
10
  */
10
11
  export async function libsCmd(flags, rest, reporter) {
11
- const interactive = !reporter.headless && !reporter.json;
12
- const spin = interactive ? startSpin("Loading your account from Dash…") : null;
13
- let me = null;
14
- try {
15
- me = await loadMe(flags, reporter, { required: false });
16
- } catch (error) {
17
- spin?.stop();
18
- reporter.warn(`Could not load account (${error.message}); showing catalog only.`);
12
+ // 入口没等目录(COMMANDS.libs.parallel):目录、账号两请求这里同 tick 并行发出,谁慢等谁。
13
+ // 命令自己的区间排最前 → 两个请求在途期间同一行转到底,结束原地落成结果行。
14
+ const land = reporter.activity("Loading your account from Dash…");
15
+ const [, outcome] = await Promise.all([
16
+ ensureCatalog({ reporter }),
17
+ loadMe(flags, reporter, { required: false }).then(
18
+ (me) => ({ me }),
19
+ (error) => ({ error })
20
+ ),
21
+ ]);
22
+ const me = outcome.me ?? null;
23
+ if (outcome.error) {
24
+ land();
25
+ reporter.warn(`Could not load account (${outcome.error.message}); showing catalog only.`);
26
+ } else {
27
+ land(me ? `Account ${me.account?.username ?? me.account?.uid}` : "Catalog (not logged in)");
19
28
  }
20
29
 
21
30
  const owned = me ? new Set(ownedLibs(me).map((lib) => lib.site)) : null;
@@ -49,8 +58,6 @@ export async function libsCmd(flags, rest, reporter) {
49
58
  });
50
59
  }
51
60
 
52
- spin?.stop(me ? `Account ${me.account?.username ?? me.account?.uid}` : "Catalog (not logged in)");
53
-
54
61
  if (reporter.json) {
55
62
  reporter.result({ account: me?.account ?? null, libraries: rows });
56
63
  return;
@@ -9,7 +9,7 @@ import { startSpin } from "../report.mjs";
9
9
  */
10
10
  export async function updateCmd(flags, _rest, reporter) {
11
11
  reporter.step(1, 2, "Checking npm for the latest @collectui/cli");
12
- const latest = await fetchLatestVersion();
12
+ const latest = await fetchLatestVersion({ reporter });
13
13
  const cmp = compareVersions(latest, CLI_VERSION);
14
14
  const summary = { current: CLI_VERSION, latest, updateAvailable: cmp > 0 };
15
15
 
@@ -1,9 +1,16 @@
1
- import { formatMeHuman, maskKey } from "../dash.mjs";
2
- import { loadMe } from "./common.mjs";
1
+ import { formatAccountHuman, maskKey } from "../dash.mjs";
2
+ import { loadAccount, loadMe } from "./common.mjs";
3
3
 
4
+ /**
5
+ * cui whoami —— 只答「我是谁」:账户名 + uid,仅此而已。
6
+ *
7
+ * 人类输出走轻量端点 GET /api/account(不做站点/key/仓库/订单聚合);完整权益看
8
+ * `cui libs`(库与 key 绑定)、`cui dash me`(全量聚合)。
9
+ * --json 契约不变:仍是全量聚合(Agent 消费 account/sites/keys/repos/orders)。
10
+ */
4
11
  export async function whoamiCmd(flags, rest, reporter) {
5
- const me = await loadMe(flags, reporter);
6
12
  if (reporter.json) {
13
+ const me = await loadMe(flags, reporter);
7
14
  reporter.result({
8
15
  account: me.account,
9
16
  sites: me.sites,
@@ -13,5 +20,5 @@ export async function whoamiCmd(flags, rest, reporter) {
13
20
  });
14
21
  return;
15
22
  }
16
- reporter.note("Account", formatMeHuman(me));
23
+ reporter.note("Account", formatAccountHuman(await loadAccount(flags, reporter)));
17
24
  }
package/src/dash.mjs CHANGED
@@ -7,9 +7,39 @@ export async function fetchMe(token, { reporter } = {}) {
7
7
  token,
8
8
  reporter,
9
9
  label: "dash /api/me",
10
+ spinner: "Loading your account from Dash…",
10
11
  });
11
12
  }
12
13
 
14
+ /**
15
+ * 轻量账户端点 GET /api/account(2026-12-01):只回账户本体(/api/me 的 account 切片),
16
+ * 不做站点/key/仓库/订单聚合——那一趟服务端 ~2s,而 `cui whoami` 只用得到 account。
17
+ * 旧 Dash 没有该路由(404)→ 退回 /api/me 取 account 切片:功能不缺,只是慢。
18
+ */
19
+ export async function fetchAccount(token, { reporter } = {}) {
20
+ const request = (path) =>
21
+ jsonRequest(`${dashUrl()}${path}`, {
22
+ token,
23
+ reporter,
24
+ label: `dash ${path}`,
25
+ spinner: "Loading your account from Dash…",
26
+ });
27
+ let data;
28
+ try {
29
+ data = await request("/api/account");
30
+ } catch (error) {
31
+ if (error?.status !== 404) throw error;
32
+ data = await request("/api/me");
33
+ }
34
+ return data?.account ?? null;
35
+ }
36
+
37
+ /** `cui whoami` 的全部输出:账户名 + uid——只答「我是谁」,权益清单看 `cui libs` / `cui dash me`。 */
38
+ export function formatAccountHuman(account) {
39
+ if (!account) return "No account data.";
40
+ return `Account: ${account.username ?? "(unknown)"} uid=${account.uid ?? "?"}`;
41
+ }
42
+
13
43
  /** Dash MCP:stateless JSON-RPC,直接 tools/list 或 tools/call。 */
14
44
  export async function dashMcpTools(token, { reporter } = {}) {
15
45
  const result = await mcpCall({
package/src/errors.mjs CHANGED
@@ -1,10 +1,12 @@
1
- /** CLI 统一错误:message 给用户看,code 决定退出码(1 通用 / 2 用法 / 3 认证)。 */
1
+ /** CLI 统一错误:message 给用户看,code 决定退出码(1 通用 / 2 用法 / 3 认证);
2
+ * status 是 HTTP 状态(网络请求失败时带,调用方按它分支)。 */
2
3
  export class CliError extends Error {
3
- constructor(message, { code = 1, hint } = {}) {
4
+ constructor(message, { code = 1, hint, status } = {}) {
4
5
  super(message);
5
6
  this.name = "CliError";
6
7
  this.exitCode = code;
7
8
  this.hint = hint;
9
+ this.status = status;
8
10
  }
9
11
  }
10
12
 
package/src/http.mjs CHANGED
@@ -10,8 +10,13 @@ function shouldRetry(status) {
10
10
  }
11
11
 
12
12
  /**
13
- * 统一 HTTP 入口:超时、退避重试、请求/响应日志(transparency)。
13
+ * 统一 HTTP 入口:超时、退避重试、请求/响应日志(transparency)、加载态。
14
14
  * 只对幂等方法(GET/HEAD)自动重试;POST 由调用方决定(MCP tools/call 重试可能重复提交)。
15
+ *
16
+ * 加载态:带 reporter 的请求在途即转 spinner(首帧与触发它的那行输出同 tick 落屏,
17
+ * 响应到了才清行,重试退避期间不断拍)——「等网络」永远有反馈,命令里不用各写各的。
18
+ * spinner 选项是在途文案(缺省 Loading…)。不传 reporter 的调用(后台更新检查)不转:
19
+ * 它与命令并行,会在 clack 提示框或输出中间乱入。
15
20
  */
16
21
  export async function httpRequest(url, options = {}) {
17
22
  const {
@@ -24,6 +29,7 @@ export async function httpRequest(url, options = {}) {
24
29
  retryUnsafe = false,
25
30
  reporter,
26
31
  label,
32
+ spinner,
27
33
  } = options;
28
34
 
29
35
  const finalHeaders = {
@@ -39,56 +45,61 @@ export async function httpRequest(url, options = {}) {
39
45
  const canRetry = retryUnsafe || method === "GET" || method === "HEAD";
40
46
  const attempts = canRetry ? retries + 1 : 1;
41
47
  let lastError;
48
+ const release = reporter?.activity?.(spinner ?? "Loading…") ?? (() => {});
42
49
 
43
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
44
- const started = Date.now();
45
- reporter?.http?.({ phase: "request", method, url, label, attempt, max: attempts });
46
- let res;
47
- try {
48
- res = await fetch(url, {
50
+ try {
51
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
52
+ const started = Date.now();
53
+ reporter?.http?.({ phase: "request", method, url, label, attempt, max: attempts });
54
+ let res;
55
+ try {
56
+ res = await fetch(url, {
57
+ method,
58
+ headers: finalHeaders,
59
+ body,
60
+ signal: AbortSignal.timeout(timeout),
61
+ redirect: "follow",
62
+ });
63
+ } catch (error) {
64
+ const ms = Date.now() - started;
65
+ reporter?.http?.({ phase: "error", method, url, label, ms, error: error.message });
66
+ lastError = error;
67
+ if (attempt < attempts) {
68
+ await sleep(500 * attempt + Math.floor(Math.random() * 250));
69
+ continue;
70
+ }
71
+ throw new CliError(`Network request failed: ${method} ${url} — ${error.message}`, {
72
+ hint: "Check your network / proxy, then retry. Dash might be temporarily unreachable.",
73
+ });
74
+ }
75
+
76
+ const text = await res.text();
77
+ const ms = Date.now() - started;
78
+ reporter?.http?.({
79
+ phase: "response",
49
80
  method,
50
- headers: finalHeaders,
51
- body,
52
- signal: AbortSignal.timeout(timeout),
53
- redirect: "follow",
81
+ url,
82
+ label,
83
+ status: res.status,
84
+ ms,
85
+ bytes: text.length,
86
+ attempt,
54
87
  });
55
- } catch (error) {
56
- const ms = Date.now() - started;
57
- reporter?.http?.({ phase: "error", method, url, label, ms, error: error.message });
58
- lastError = error;
59
- if (attempt < attempts) {
88
+
89
+ if (res.ok) return { res, text };
90
+
91
+ if (attempt < attempts && shouldRetry(res.status)) {
60
92
  await sleep(500 * attempt + Math.floor(Math.random() * 250));
61
93
  continue;
62
94
  }
63
- throw new CliError(`Network request failed: ${method} ${url} — ${error.message}`, {
64
- hint: "Check your network / proxy, then retry. Dash might be temporarily unreachable.",
65
- });
66
- }
67
-
68
- const text = await res.text();
69
- const ms = Date.now() - started;
70
- reporter?.http?.({
71
- phase: "response",
72
- method,
73
- url,
74
- label,
75
- status: res.status,
76
- ms,
77
- bytes: text.length,
78
- attempt,
79
- });
80
-
81
- if (res.ok) return { res, text };
82
95
 
83
- if (attempt < attempts && shouldRetry(res.status)) {
84
- await sleep(500 * attempt + Math.floor(Math.random() * 250));
85
- continue;
96
+ return { res, text, error: true };
86
97
  }
87
98
 
88
- return { res, text, error: true };
99
+ throw new CliError(`Network request failed: ${method} ${url} — ${lastError?.message ?? "unknown error"}`);
100
+ } finally {
101
+ release();
89
102
  }
90
-
91
- throw new CliError(`Network request failed: ${method} ${url} — ${lastError?.message ?? "unknown error"}`);
92
103
  }
93
104
 
94
105
  export async function jsonRequest(url, options = {}) {
@@ -107,6 +118,7 @@ export async function jsonRequest(url, options = {}) {
107
118
  `HTTP ${out.res.status}`;
108
119
  throw new CliError(`${options.label ?? url} failed: ${message}`, {
109
120
  code: out.res.status === 401 || out.res.status === 403 ? 3 : 1,
121
+ status: out.res.status, // 调用方按 HTTP 状态分支用(如新端点 404 → 退回旧端点)
110
122
  hint:
111
123
  out.res.status === 401
112
124
  ? "Run `cui login` again (or pass --token) — your PAT may be missing, revoked or expired."
@@ -132,6 +144,7 @@ export async function mcpCall({ base, token, method, params, reporter, id = 1 })
132
144
  body,
133
145
  reporter,
134
146
  label: `mcp:${method}`,
147
+ spinner: "Calling Dash MCP…",
135
148
  headers: { "Content-Type": "application/json" },
136
149
  timeout: 30_000,
137
150
  retries: 0,
package/src/login.mjs CHANGED
@@ -12,6 +12,7 @@ export async function verifyToken(token, { reporter } = {}) {
12
12
  token,
13
13
  reporter,
14
14
  label: "dash /api/me",
15
+ spinner: "Verifying your PAT with Dash…",
15
16
  headers: { Accept: "application/json" },
16
17
  });
17
18
  }
package/src/report.mjs CHANGED
@@ -4,6 +4,7 @@ import * as p from "@clack/prompts";
4
4
  * 透明输出层:
5
5
  * - TTY / 人类模式:@clack/prompts(p CLI 同款)的 intro/log/step/note/outro
6
6
  * - 无头 / Agent 模式(--json 或非 TTY):逐行 JSON event,stdout 只出机器可读内容
7
+ * - 加载态:网络请求在途即转 spinner(createActivity),人类可读输出落地前自动让路
7
8
  *
8
9
  * 所有输出都过 redact():PAT、CLI key、MCP key 永远不会出现在日志里。
9
10
  */
@@ -14,9 +15,18 @@ export function createReporter({
14
15
  secrets = [],
15
16
  verbose = false,
16
17
  forceHeadless = false,
18
+ stream = process.stdout,
17
19
  } = {}) {
18
20
  let secretList = [...secrets].filter((s) => typeof s === "string" && s.length >= 4);
19
21
  const headless = json || forceHeadless || !process.stdout.isTTY;
22
+ // --json:加载态整套不存在(零字节),机器可读契约不受搅动
23
+ const activity = json ? NO_ACTIVITY : createActivity({ stream });
24
+
25
+ /** 人类可读输出统一先给 spinner 让路(清行),再落字。 */
26
+ const say = (write) => {
27
+ activity.pause();
28
+ write();
29
+ };
20
30
 
21
31
  function redact(value) {
22
32
  let out = typeof value === "string" ? value : String(value ?? "");
@@ -43,6 +53,7 @@ export function createReporter({
43
53
  function raw(msg, level = "info") {
44
54
  if (json) return;
45
55
  const text = redact(msg);
56
+ activity.pause();
46
57
  if (level === "error") p.log.error(text);
47
58
  else if (level === "warn") p.log.warn(text);
48
59
  else if (level === "success") p.log.success(text);
@@ -58,15 +69,19 @@ export function createReporter({
58
69
  addSecrets,
59
70
  redact,
60
71
  headlessMode: headless,
72
+ /** 登记一段「在等」的区间(TTY 下即 spinner),返回 release(finalMessage?)。 */
73
+ activity: activity.acquire,
74
+ /** 进程收尾:清行、还光标,在途区间一并作废。 */
75
+ settleLoading: activity.drop,
61
76
 
62
77
  intro(title) {
63
78
  if (json) emit({ event: "intro", title: redact(title) });
64
- else p.intro(redact(title));
79
+ else say(() => p.intro(redact(title)));
65
80
  },
66
81
 
67
82
  outro(title) {
68
83
  if (json) emit({ event: "outro", title: redact(title) });
69
- else p.outro(redact(title));
84
+ else say(() => p.outro(redact(title)));
70
85
  },
71
86
 
72
87
  info(msg) {
@@ -91,21 +106,23 @@ export function createReporter({
91
106
 
92
107
  step(index, total, title) {
93
108
  if (json) emit({ event: "step", index, total, title: redact(title) });
94
- else if (typeof p.log.step === "function") p.log.step(redact(`[${index}/${total}] ${title}`));
95
- else p.log.info(redact(`[${index}/${total}] ${title}`));
109
+ else if (typeof p.log.step === "function") say(() => p.log.step(redact(`[${index}/${total}] ${title}`)));
110
+ else say(() => p.log.info(redact(`[${index}/${total}] ${title}`)));
96
111
  },
97
112
 
98
113
  note(title, body) {
99
114
  if (json) emit({ event: "note", title: redact(title), body: redact(body) });
100
- else p.note(redact(body), redact(title));
115
+ else say(() => p.note(redact(body), redact(title)));
101
116
  },
102
117
 
103
118
  http(payload) {
104
119
  if (json) emit({ event: "http", ...payload, url: redact(payload.url) });
105
120
  else if (verbose && payload.phase === "request") {
106
- p.log.info(redact(` → ${payload.method} ${payload.url}${payload.attempt > 1 ? ` (retry ${payload.attempt})` : ""}`));
121
+ say(() =>
122
+ p.log.info(redact(` → ${payload.method} ${payload.url}${payload.attempt > 1 ? ` (retry ${payload.attempt})` : ""}`))
123
+ );
107
124
  } else if (verbose && payload.phase === "response") {
108
- p.log.info(redact(` ← ${payload.status} ${payload.url} (${payload.ms}ms)`));
125
+ say(() => p.log.info(redact(` ← ${payload.status} ${payload.url} (${payload.ms}ms)`)));
109
126
  }
110
127
  },
111
128
 
@@ -127,29 +144,32 @@ export function createReporter({
127
144
  const icon =
128
145
  status === "created" ? "+" : status === "updated" ? "~" : status === "unchanged" ? "=" : "·";
129
146
  const line = `${icon} ${summary ?? kind}${path ? ` ${path}` : ""}`;
130
- if (dryRun || status === "planned") p.log.info(redact(line));
131
- else p.log.success(redact(line));
132
- if (!json && changes.length && verbose) {
133
- for (const c of changes) p.log.info(redact(` · ${c}`));
134
- }
147
+ say(() => {
148
+ if (dryRun || status === "planned") p.log.info(redact(line));
149
+ else p.log.success(redact(line));
150
+ if (!json && changes.length && verbose) {
151
+ for (const c of changes) p.log.info(redact(` · ${c}`));
152
+ }
153
+ });
135
154
  },
136
155
 
137
156
  preview(label, text) {
138
157
  const body = redact(text);
139
158
  if (json) emit({ event: "preview", label: redact(label), text: body });
140
- else if (verbose || dryRun) p.note(body, redact(label));
159
+ else if (verbose || dryRun) say(() => p.note(body, redact(label)));
141
160
  },
142
161
 
143
162
  result(data) {
144
163
  if (json) emit({ event: "result", ...sanitize(data, redact) });
145
164
  else {
146
165
  const lines = flattenResult(data).map(redact);
147
- if (lines.length) p.note(lines.join("\n"), "Result");
166
+ if (lines.length) say(() => p.note(lines.join("\n"), "Result"));
148
167
  }
149
168
  },
150
169
 
151
170
  async confirm(message, { defaultValue = true } = {}) {
152
171
  if (yes || headless) return true;
172
+ activity.pause(); // clack 提示框接管终端期间,屏幕上不能有 spinner 行
153
173
  const answer = await p.confirm({ message: redact(message), initialValue: defaultValue });
154
174
  if (p.isCancel(answer)) {
155
175
  p.cancel("Cancelled.");
@@ -162,6 +182,7 @@ export function createReporter({
162
182
  if (headless) {
163
183
  throw new Error(`Interactive selection required: ${message}. Pass flags instead.`);
164
184
  }
185
+ activity.pause();
165
186
  const answer = await p.select({ message: redact(message), options });
166
187
  if (p.isCancel(answer)) {
167
188
  p.cancel("Cancelled.");
@@ -226,25 +247,40 @@ export function formatTable(rows, columns) {
226
247
  * 1. 不擦行——`\x1b[K` 每帧先擦后写,擦除→空白的空窗在部分终端被渲染成
227
248
  * 一帧空行,这就是「整行在闪」。改为首帧铺满整行,后续帧 `\r` 回行首
228
249
  * 等长覆写(braille 帧全部单列等宽,每帧渲染串严格等长,必然盖满旧行)。
250
+ * set(message) 换文案同理:新文案更短就补空格到旧行长度,照样不擦行。
229
251
  * 2. 隐藏光标——不藏的话块状光标每帧在行首/行尾来回跳,观感同闪。
230
- * stop 恢复;进程意外退出由 exit 钩子兜底恢复,终端不会丢光标。
252
+ * stop 恢复;进程正常退出由 exit 钩子兜底(Ctrl+C 等信号不触发 exit 钩子,
253
+ * 由 createActivity 接管)。
231
254
  * 3. 单次 write 整串——不拆多次写,避免终端分批渲染出中间态。
232
255
  * 仅 TTY 用;stop(finalMessage) 清行后打印终态(省略则只清行),幂等。
233
256
  */
234
257
  export function startSpin(message, { stream = process.stdout, interval = 90 } = {}) {
235
- if (!stream.isTTY) return { stop: () => {} };
258
+ if (!stream.isTTY) return { stop: () => {}, set: () => {} };
236
259
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
237
- const render = (frame) => `${frame} ${message}`;
260
+ let current = message;
261
+ let shown = 0; // 行上已落屏的文案长度——下一帧覆写的基准
238
262
  let i = 0;
239
263
  let stopped = false;
240
264
  const restoreCursor = () => stream.write("\x1b[?25h");
241
265
  process.once("exit", restoreCursor);
242
- stream.write(`\x1b[?25l${render(frames[0])}`);
266
+ const draw = () => {
267
+ const pad = " ".repeat(Math.max(0, shown - current.length));
268
+ stream.write(`\r${frames[i]} ${current}${pad}`);
269
+ shown = current.length;
270
+ };
271
+ stream.write(`\x1b[?25l${frames[i]} ${current}`);
272
+ shown = current.length;
243
273
  const timer = setInterval(() => {
244
- i += 1;
245
- stream.write(`\r${render(frames[i % frames.length])}`);
274
+ i = (i + 1) % frames.length;
275
+ draw();
246
276
  }, interval);
247
277
  return {
278
+ /** 原地换文案(切换加载阶段):随下一帧一起换,不擦行、不断拍。 */
279
+ set(next) {
280
+ if (stopped || next === current) return;
281
+ current = next;
282
+ draw();
283
+ },
248
284
  stop(finalMessage) {
249
285
  if (stopped) return;
250
286
  stopped = true;
@@ -255,3 +291,98 @@ export function startSpin(message, { stream = process.stdout, interval = 90 } =
255
291
  },
256
292
  };
257
293
  }
294
+
295
+ const NO_ACTIVITY = {
296
+ acquire: () => () => {},
297
+ pause: () => {},
298
+ drop: () => {},
299
+ };
300
+
301
+ /**
302
+ * 加载态:把「在等」的区间画成一行 spinner。
303
+ * - acquire(message) 登记一段在途区间,返回 release()(幂等)。屏幕上没有 spinner 时
304
+ * 当拍就写首帧——与触发它的那行输出(品牌 / 上一条结果)同一个 tick 落屏,
305
+ * 不存在「出了品牌却没动静」的空窗。
306
+ * - 多段区间重叠只占一行:显示最先登记的文案,头部结束原地切下一条。
307
+ * - release(finalMessage):区间全部结束时 spinner 行还在屏上,就原地落成这一行
308
+ * (与旧 startSpin().stop(finalMessage) 同款落地,不清行再写)。
309
+ * - pause() 给人类可读输出让路(清行、还光标);输出落地后若还有区间在等,下一拍
310
+ * 在新行接着转。让路后同一 tick 内区间就结束的,一帧都不会多画。
311
+ * - Ctrl+C / SIGTERM:清行、还光标再退。默认信号处置不触发 exit 钩子——终端会
312
+ * 被留下一个藏死的光标 + 冻住的 spinner 行(PTY 实测)。
313
+ */
314
+ function createActivity({ stream, interval = 90 }) {
315
+ if (!stream.isTTY) return NO_ACTIVITY;
316
+ const queue = [];
317
+ let spin = null; // 屏幕上正在转的 spinner(null = 没有 spinner 行)
318
+ let resume = null; // 让路后等下一拍在新行接着转的定时器
319
+ let hooked = false;
320
+ const clearResume = () => {
321
+ if (resume) {
322
+ clearTimeout(resume);
323
+ resume = null;
324
+ }
325
+ };
326
+ const start = () => {
327
+ clearResume();
328
+ spin = startSpin(queue[0].message, { stream, interval });
329
+ };
330
+ const onSigint = () => {
331
+ spin?.stop();
332
+ process.exit(130);
333
+ };
334
+ const onSigterm = () => {
335
+ spin?.stop();
336
+ process.exit(143);
337
+ };
338
+ function hook(on) {
339
+ if (on === hooked) return;
340
+ hooked = on;
341
+ const op = on ? "once" : "removeListener";
342
+ process[op]("SIGINT", onSigint);
343
+ process[op]("SIGTERM", onSigterm);
344
+ }
345
+ return {
346
+ acquire(message) {
347
+ const entry = { message };
348
+ queue.push(entry);
349
+ hook(true);
350
+ if (!spin) start();
351
+ let released = false;
352
+ return (finalMessage) => {
353
+ if (released) return;
354
+ released = true;
355
+ const at = queue.indexOf(entry);
356
+ if (at !== -1) queue.splice(at, 1);
357
+ if (queue.length > 0) {
358
+ if (at === 0 && spin) spin.set(queue[0].message);
359
+ return;
360
+ }
361
+ clearResume();
362
+ hook(false);
363
+ if (spin) spin.stop(finalMessage);
364
+ else if (finalMessage != null) stream.write(`${finalMessage}\n`);
365
+ spin = null;
366
+ };
367
+ },
368
+ pause() {
369
+ if (spin) {
370
+ spin.stop();
371
+ spin = null;
372
+ }
373
+ if (!resume && queue.length > 0) {
374
+ resume = setTimeout(() => {
375
+ resume = null;
376
+ if (queue.length > 0 && !spin) start();
377
+ }, interval);
378
+ }
379
+ },
380
+ drop() {
381
+ queue.length = 0;
382
+ clearResume();
383
+ hook(false);
384
+ spin?.stop();
385
+ spin = null;
386
+ },
387
+ };
388
+ }
package/src/update.mjs CHANGED
@@ -78,8 +78,14 @@ export function decideUpdate({
78
78
  }
79
79
 
80
80
  /** registry latest → 版本号;失败抛错(调用方决定吞还是报)。 */
81
- export async function fetchLatestVersion({ timeout = 8_000 } = {}) {
82
- const out = await httpRequest(REGISTRY_LATEST, { timeout, retries: 1 });
81
+ export async function fetchLatestVersion({ timeout = 8_000, reporter } = {}) {
82
+ // 带 reporter 才转 spinner:前台 `cui update` 传;后台检查不传(与命令并行,不能乱入)
83
+ const out = await httpRequest(REGISTRY_LATEST, {
84
+ timeout,
85
+ retries: 1,
86
+ reporter,
87
+ spinner: "Checking npm for updates…",
88
+ });
83
89
  if (!out.res.ok) throw new Error(`registry ${out.res.status}`);
84
90
  const parsed = JSON.parse(out.text);
85
91
  const v = parsed?.version;