@collectui/cli 0.2.1 → 0.2.3
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 +20 -7
- package/package.json +1 -1
- package/src/args.mjs +4 -0
- package/src/banner.mjs +62 -0
- package/src/cli.mjs +10 -1
- package/src/commands/login.mjs +1 -0
- package/src/commands/setup.mjs +2 -0
- package/src/commands/update.mjs +48 -0
- package/src/http.mjs +2 -2
- package/src/login.mjs +70 -71
- package/src/update.mjs +172 -0
package/README.md
CHANGED
|
@@ -29,18 +29,20 @@ collectui --version
|
|
|
29
29
|
collectui login
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
**OAuth 式浏览器授权**:CLI 起一个本机回调监听并打开 Dash 的 `/authorize` 授权页,
|
|
33
|
+
登录态下点一次「授权」——Dash 自动创建一条 `collectui-cli` PAT 并把明文回传本机
|
|
34
|
+
(`127.0.0.1` 回环,全程无需复制粘贴)。PAT 保存到 `~/.collectui/config.json`(`chmod 600`)。
|
|
33
35
|
|
|
34
|
-
|
|
36
|
+
无浏览器场景(CI / ssh / 远程机):
|
|
35
37
|
|
|
36
38
|
```bash
|
|
37
|
-
|
|
38
|
-
#
|
|
39
|
-
collectui login --token dpat_... --json
|
|
39
|
+
collectui login --pat # 终端粘贴 PAT(隐藏输入)
|
|
40
|
+
COLLECTUI_TOKEN=dpat_... collectui whoami --json # 或完全 headless
|
|
41
|
+
collectui login --token dpat_... --json # 或显式传入
|
|
40
42
|
```
|
|
41
43
|
|
|
42
|
-
>
|
|
43
|
-
>
|
|
44
|
+
> 授权页与 PAT 创建都在 Dash 完成(服务端只把明文回传给 `127.0.0.1`/`localhost`
|
|
45
|
+
> 回调,CLI 侧带随机 secret 路径 + state 校验);本机回环即用即弃。
|
|
44
46
|
|
|
45
47
|
## 看账户与库
|
|
46
48
|
|
|
@@ -164,6 +166,17 @@ collectui doctor # 登录、account、Dash MCP、项目 registries/en
|
|
|
164
166
|
collectui doctor --deep # 再对每个已拥有库做一次 registry 探测(会消耗额度,慎用)
|
|
165
167
|
```
|
|
166
168
|
|
|
169
|
+
## 自动更新
|
|
170
|
+
|
|
171
|
+
CLI 每 12 小时后台查一次 npm(本地缓存 `~/.collectui/update-check.json`,绝不阻塞命令)。
|
|
172
|
+
交互终端下**默认自动更新**:发现新版即后台 `npm i -g @collectui/cli@latest`,
|
|
173
|
+
下次运行生效,当前命令不受影响。
|
|
174
|
+
|
|
175
|
+
- 关掉:`collectui update --off`(仍会提示新版,只是不自动动手);
|
|
176
|
+
或环境变量 `COLLECTUI_NO_AUTO_UPDATE=1`(CI / Agent 全静默)
|
|
177
|
+
- 手动:`collectui update`(前台看着装);`collectui update --check`(只查不装)
|
|
178
|
+
- `--json` / 非 TTY / `npx` 临时跑:完全不碰更新逻辑
|
|
179
|
+
|
|
167
180
|
## 支持的库
|
|
168
181
|
|
|
169
182
|
| 站点 slug | 库 | registry scope | MCP |
|
package/package.json
CHANGED
package/src/args.mjs
CHANGED
package/src/banner.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { stdout } from "node:process";
|
|
2
|
+
import { CLI_VERSION } from "./version.mjs";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 彩色 ASCII 品牌 banner(login / init 这类仪式感命令的开机画面)。
|
|
6
|
+
* - 支持 truecolor 的终端逐行渐变(青 → 紫);仅 256 色/其他 → 256 色近似;
|
|
7
|
+
* - NO_COLOR、非 TTY、headless 一律降级为无色纯文本(Agent/CI 永远干净)。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const GLYPH = [
|
|
11
|
+
" ██████╗ ██╗ ██╗██╗",
|
|
12
|
+
"██╔════╝ ██║ ██║██║",
|
|
13
|
+
"██║ ███╗██║ ██║██║",
|
|
14
|
+
"██║ ██║██║ ██║██║",
|
|
15
|
+
"╚██████╔╝╚██████╔╝██║",
|
|
16
|
+
" ╚═════╝ ╚═════╝ ╚═╝",
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
const TAGLINE = "One CLI for every shadcn library";
|
|
20
|
+
|
|
21
|
+
// 青 → 紫(Tailwind cyan-400 → violet-400)
|
|
22
|
+
const FROM = [34, 211, 238];
|
|
23
|
+
const TO = [167, 139, 250];
|
|
24
|
+
|
|
25
|
+
const GRAY = "\x1b[90m";
|
|
26
|
+
const RESET = "\x1b[0m";
|
|
27
|
+
|
|
28
|
+
function colorSupport() {
|
|
29
|
+
if (process.env.NO_COLOR) return "none";
|
|
30
|
+
if (!stdout.isTTY) return "none";
|
|
31
|
+
const ct = String(process.env.COLORTERM ?? "");
|
|
32
|
+
if (ct.includes("truecolor") || ct.includes("24bit")) return "truecolor";
|
|
33
|
+
// iTerm2/Terminal.app/VSCode/Windows Terminal 等现代终端默认按 256 起步
|
|
34
|
+
return "256";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function lerp(a, b, t) {
|
|
38
|
+
return Math.round(a + (b - a) * t);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function rgbColor(at, text) {
|
|
42
|
+
const t = GLYPH.length <= 1 ? 0 : at / (GLYPH.length - 1);
|
|
43
|
+
return `\x1b[38;2;${lerp(FROM[0], TO[0], t)};${lerp(FROM[1], TO[1], t)};${lerp(FROM[2], TO[2], t)}m${text}${RESET}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function ansi256(at, text) {
|
|
47
|
+
const codes = [44, 44, 45, 99, 134, 140];
|
|
48
|
+
return `\x1b[38;5;${codes[Math.min(at, codes.length - 1)]}m${text}${RESET}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function showBanner(reporter) {
|
|
52
|
+
if (reporter?.headless) return; // --json / 非 TTY:输出保持机器可读,不开机画面
|
|
53
|
+
const support = colorSupport();
|
|
54
|
+
const paint = support === "truecolor" ? rgbColor : support === "256" ? ansi256 : null;
|
|
55
|
+
for (let i = 0; i < GLYPH.length; i += 1) {
|
|
56
|
+
const line = paint ? paint(i, GLYPH[i]) : GLYPH[i];
|
|
57
|
+
console.log(line);
|
|
58
|
+
}
|
|
59
|
+
const tag = support === "none" ? `${TAGLINE} · v${CLI_VERSION}` : `${GRAY}${TAGLINE} · v${CLI_VERSION}${RESET}`;
|
|
60
|
+
console.log(tag);
|
|
61
|
+
console.log();
|
|
62
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -14,6 +14,7 @@ import { CLI_NAME, CLI_VERSION } from "./version.mjs";
|
|
|
14
14
|
import { collectSecrets, readConfig, resolveToken } from "./config.mjs";
|
|
15
15
|
import { CliError, usageError } from "./errors.mjs";
|
|
16
16
|
import { createReporter } from "./report.mjs";
|
|
17
|
+
import { startBackgroundUpdate } from "./update.mjs";
|
|
17
18
|
import { loginCmd, logoutCmd } from "./commands/login.mjs";
|
|
18
19
|
import { whoamiCmd } from "./commands/whoami.mjs";
|
|
19
20
|
import { libsCmd } from "./commands/libs.mjs";
|
|
@@ -24,6 +25,7 @@ import { doctorCmd } from "./commands/doctor.mjs";
|
|
|
24
25
|
import { mcpCmd } from "./commands/mcp.mjs";
|
|
25
26
|
import { dashCmd } from "./commands/dash.mjs";
|
|
26
27
|
import { skillCmd } from "./commands/skill.mjs";
|
|
28
|
+
import { updateCmd } from "./commands/update.mjs";
|
|
27
29
|
|
|
28
30
|
const HELP = `collectui ${CLI_VERSION} — one CLI for every shadcn library on CollectUI Dash
|
|
29
31
|
|
|
@@ -31,7 +33,7 @@ Usage:
|
|
|
31
33
|
collectui <command> [args] [flags]
|
|
32
34
|
|
|
33
35
|
Commands:
|
|
34
|
-
login
|
|
36
|
+
login Authorize CollectUI CLI in your browser (OAuth-style)
|
|
35
37
|
logout Remove the saved PAT
|
|
36
38
|
whoami, me Show account, libraries, bound keys and repos
|
|
37
39
|
libs List every library, ownership and key status
|
|
@@ -42,6 +44,7 @@ Commands:
|
|
|
42
44
|
dash <sub> Dash MCP: me, repos, download, feedback, tools, call
|
|
43
45
|
skill [dir] Install the agent skill (.claude/skills/collectui)
|
|
44
46
|
doctor Verify login, registries, env and MCP config
|
|
47
|
+
update Update the CLI now (--check only / --off/--on toggles auto-update)
|
|
45
48
|
|
|
46
49
|
Global options:
|
|
47
50
|
--token <PAT> Dash PAT (dpat_...); overrides saved login
|
|
@@ -51,6 +54,7 @@ Global options:
|
|
|
51
54
|
--dry-run Print the full plan; write nothing
|
|
52
55
|
--verbose, -v Show HTTP requests, diffs and per-entry decisions
|
|
53
56
|
--no-open Do not open a browser during login
|
|
57
|
+
--pat login: paste a PAT instead of browser authorization (no-browser hosts)
|
|
54
58
|
--no-install init: skip dependency installation
|
|
55
59
|
--no-mcp init/configure: skip MCP configuration
|
|
56
60
|
--no-dash-mcp Do not add the collectui-dash MCP server
|
|
@@ -86,6 +90,7 @@ Environment:
|
|
|
86
90
|
COLLECTUI_DASH_URL default https://dash.collectui.pro
|
|
87
91
|
COLLECTUI_REGISTRY_URL default https://registry.collectui.pro
|
|
88
92
|
COLLECTUI_HOME config directory override
|
|
93
|
+
COLLECTUI_NO_AUTO_UPDATE=1 disable background update check (CI/Agent silent)
|
|
89
94
|
`;
|
|
90
95
|
|
|
91
96
|
const COMMANDS = {
|
|
@@ -100,6 +105,7 @@ const COMMANDS = {
|
|
|
100
105
|
dash: { run: dashCmd, aliases: [] },
|
|
101
106
|
skill: { run: skillCmd, aliases: ["install-skill"] },
|
|
102
107
|
doctor: { run: doctorCmd, aliases: ["check"] },
|
|
108
|
+
update: { run: updateCmd, aliases: ["upgrade"] },
|
|
103
109
|
};
|
|
104
110
|
|
|
105
111
|
function findCommand(name) {
|
|
@@ -157,6 +163,9 @@ async function main() {
|
|
|
157
163
|
const reporter = makeReporter(flags, token);
|
|
158
164
|
if (token) reporter.addSecrets([token]);
|
|
159
165
|
|
|
166
|
+
// 自更新:交互 TTY 下后台检查/自动更(headless/CI 由门控静默跳过)
|
|
167
|
+
startBackgroundUpdate(reporter, { config: readConfig() });
|
|
168
|
+
|
|
160
169
|
await command.run(flags, rest, reporter);
|
|
161
170
|
}
|
|
162
171
|
|
package/src/commands/login.mjs
CHANGED
package/src/commands/setup.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { fetchMe } from "../dash.mjs";
|
|
|
10
10
|
import { planMcpConfig, describeEntries } from "../mcp.mjs";
|
|
11
11
|
import { detectPackageManager, planProjectConfig } from "../project.mjs";
|
|
12
12
|
import { planManifest, planScaffold } from "../scaffold.mjs";
|
|
13
|
+
import { showBanner } from "../banner.mjs";
|
|
13
14
|
import { selectLibs } from "./common.mjs";
|
|
14
15
|
|
|
15
16
|
const DEFAULT_CLIENTS = ["claude", "cursor", "vscode"];
|
|
@@ -60,6 +61,7 @@ function isNonEmptyDir(dir) {
|
|
|
60
61
|
*/
|
|
61
62
|
export async function runSetup({ flags, rest = [], reporter, mode }) {
|
|
62
63
|
reporter.intro(`CollectUI CLI · ${mode}`);
|
|
64
|
+
if (mode === "init") showBanner(reporter);
|
|
63
65
|
|
|
64
66
|
let token = resolveToken(flags);
|
|
65
67
|
if (!token) {
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { CLI_VERSION } from "../version.mjs";
|
|
2
|
+
import { compareVersions, fetchLatestVersion, runManualUpdate } from "../update.mjs";
|
|
3
|
+
import { writeConfig } from "../config.mjs";
|
|
4
|
+
import { CliError } from "../errors.mjs";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* collectui update 手动立即更新(前台,看着跑)
|
|
8
|
+
* collectui update --check 只查不更(打 registry,不走缓存)
|
|
9
|
+
* collectui update --off/--on 关/开自动更新(写 config.autoUpdate)
|
|
10
|
+
*/
|
|
11
|
+
export async function updateCmd(flags, _rest, reporter) {
|
|
12
|
+
if (flags.off || flags.on) {
|
|
13
|
+
if (flags.off && flags.on) {
|
|
14
|
+
throw new CliError("--off and --on are mutually exclusive.", { code: 2 });
|
|
15
|
+
}
|
|
16
|
+
const next = writeConfig({ autoUpdate: !flags.off });
|
|
17
|
+
reporter.result({ autoUpdate: next.autoUpdate !== false });
|
|
18
|
+
reporter.outro(next.autoUpdate !== false ? "Auto-update enabled." : "Auto-update disabled (still notifies on new versions).");
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
reporter.step(1, 2, "Checking npm for the latest @collectui/cli");
|
|
23
|
+
const latest = await fetchLatestVersion();
|
|
24
|
+
const cmp = compareVersions(latest, CLI_VERSION);
|
|
25
|
+
const summary = { current: CLI_VERSION, latest, updateAvailable: cmp > 0 };
|
|
26
|
+
|
|
27
|
+
if (cmp <= 0) {
|
|
28
|
+
reporter.result(summary);
|
|
29
|
+
reporter.outro(`Already on the latest version (${CLI_VERSION}).`);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (flags.check) {
|
|
34
|
+
reporter.result(summary);
|
|
35
|
+
reporter.outro(`Update available: ${CLI_VERSION} → ${latest} (re-run without --check to install).`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
reporter.step(2, 2, `Installing @collectui/cli@latest (${CLI_VERSION} → ${latest})`);
|
|
40
|
+
const res = runManualUpdate();
|
|
41
|
+
if (!res || res.status !== 0) {
|
|
42
|
+
throw new CliError(`npm install failed${res?.status ? ` (exit ${res.status})` : ""}.`, {
|
|
43
|
+
hint: "Run `npm i -g @collectui/cli` manually to see the npm error; check global-prefix permissions (sudo/nvm).",
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
reporter.result({ ...summary, updated: true });
|
|
47
|
+
reporter.outro(`Updated to ${latest}. Re-run commands to pick it up.`);
|
|
48
|
+
}
|
package/src/http.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CliError } from "./errors.mjs";
|
|
2
|
+
import { CLI_VERSION } from "./version.mjs";
|
|
2
3
|
|
|
3
|
-
const
|
|
4
|
-
const UA = `collectui-cli/${VERSION} (Node.js ${process.version}; +https://dash.collectui.pro)`;
|
|
4
|
+
const UA = `collectui-cli/${CLI_VERSION} (Node.js ${process.version}; +https://dash.collectui.pro)`;
|
|
5
5
|
|
|
6
6
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
7
7
|
|
package/src/login.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
|
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
3
|
import { createServer } from "node:http";
|
|
4
4
|
import * as p from "@clack/prompts";
|
|
5
|
+
import { showBanner } from "./banner.mjs";
|
|
5
6
|
import { clearConfig, configFile, dashUrl, writeConfig } from "./config.mjs";
|
|
6
7
|
import { authError } from "./errors.mjs";
|
|
7
8
|
import { jsonRequest } from "./http.mjs";
|
|
@@ -33,10 +34,12 @@ export function saveSession(token, me, { reporter } = {}) {
|
|
|
33
34
|
}
|
|
34
35
|
|
|
35
36
|
/**
|
|
36
|
-
*
|
|
37
|
-
* 1.
|
|
38
|
-
* 2.
|
|
39
|
-
*
|
|
37
|
+
* 登录(OAuth 浏览器授权为主通道):
|
|
38
|
+
* 1. 本地起 127.0.0.1 回调监听(带随机 secret 路径 + state 校验)
|
|
39
|
+
* 2. 打开 Dash 的 /authorize 授权页(登录态下点一次「授权」,Dash 建好 PAT
|
|
40
|
+
* 并把明文 redirect 回本机回调,全程无需复制粘贴)
|
|
41
|
+
* 3. 无浏览器场景(CI / 远程 / ssh)用 `collectui login --pat` 粘贴 PAT,
|
|
42
|
+
* 或 headless 下 --token / COLLECTUI_TOKEN / stdin
|
|
40
43
|
*
|
|
41
44
|
* 无头模式(--json / 非 TTY):从 --token / 环境变量 / stdin 取 PAT,绝不弹交互。
|
|
42
45
|
*/
|
|
@@ -46,8 +49,10 @@ export async function login({
|
|
|
46
49
|
timeout = 180_000,
|
|
47
50
|
reporter,
|
|
48
51
|
skipVerify = false,
|
|
52
|
+
pat = false,
|
|
49
53
|
}) {
|
|
50
54
|
reporter.intro("CollectUI CLI · login");
|
|
55
|
+
showBanner(reporter);
|
|
51
56
|
|
|
52
57
|
let token = providedToken || process.env.COLLECTUI_TOKEN || process.env.DASH_PAT || "";
|
|
53
58
|
token = token.trim();
|
|
@@ -64,60 +69,59 @@ export async function login({
|
|
|
64
69
|
`${dashUrl()} (top-right 「API 密钥」).`,
|
|
65
70
|
});
|
|
66
71
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
if (!token && pat) {
|
|
73
|
+
// --pat:无浏览器场景(CI / ssh / 远程),单次隐藏输入,等用户贴完或 Ctrl+C
|
|
74
|
+
const pasted = await promptToken();
|
|
75
|
+
if (pasted === null) throw authError("Login cancelled.");
|
|
76
|
+
token = tokenOrThrow(pasted);
|
|
77
|
+
}
|
|
71
78
|
if (!token) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
reporter.info("
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const remaining = timeout - (Date.now() - started);
|
|
88
|
-
if (remaining <= 0) throw authError("Login timed out.", { hint: "Re-run `collectui login`." });
|
|
89
|
-
answer = await Promise.race([
|
|
90
|
-
callback.waitForToken(remaining),
|
|
91
|
-
promptToken(Math.min(remaining, 120_000)),
|
|
92
|
-
]);
|
|
93
|
-
if (!answer) {
|
|
94
|
-
// 用户回车但没贴内容:继续等回调/再次提示,直到超时
|
|
95
|
-
if (!callback.pending) break;
|
|
79
|
+
// OAuth 主通道:浏览器授权后 Dash 直接回传,不用复制粘贴
|
|
80
|
+
const callback = startCallbackServer();
|
|
81
|
+
try {
|
|
82
|
+
const state = randomBytes(8).toString("hex");
|
|
83
|
+
const cbUrl = await callback.url();
|
|
84
|
+
const authUrl =
|
|
85
|
+
`${dashUrl()}/authorize?state=${state}&callback=${encodeURIComponent(cbUrl)}`;
|
|
86
|
+
reporter.info("Authorize CollectUI CLI in your browser:");
|
|
87
|
+
reporter.info(" " + authUrl);
|
|
88
|
+
if (!noOpen) {
|
|
89
|
+
const opened = openBrowser(authUrl);
|
|
90
|
+
if (opened) reporter.info("Opened the authorize page in your browser.");
|
|
91
|
+
else reporter.warn("Could not open a browser automatically; open the URL above manually.");
|
|
92
|
+
} else {
|
|
93
|
+
reporter.info("--no-open: open the URL above yourself.");
|
|
96
94
|
}
|
|
95
|
+
reporter.info(
|
|
96
|
+
`Waiting for the browser to come back (timeout ${Math.round(timeout / 1000)}s)… ` +
|
|
97
|
+
`No browser here? Re-run with --pat to paste a PAT.`
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
const answer = await callback.waitForToken(timeout);
|
|
101
|
+
token = tokenOrThrow(answer);
|
|
102
|
+
} finally {
|
|
103
|
+
callback.close();
|
|
97
104
|
}
|
|
98
|
-
token = tokenOrThrow(answer);
|
|
99
105
|
}
|
|
106
|
+
}
|
|
100
107
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
} else {
|
|
113
|
-
reporter.warn("--no-verify: token saved without checking it. Run `collectui whoami` to verify.");
|
|
108
|
+
let me = null;
|
|
109
|
+
if (!skipVerify) {
|
|
110
|
+
try {
|
|
111
|
+
me = await verifyToken(token, { reporter });
|
|
112
|
+
} catch (error) {
|
|
113
|
+
throw authError(`PAT verification failed: ${error.message}`, {
|
|
114
|
+
hint:
|
|
115
|
+
"Make sure you copied the full dpat_ token and that it is still active in " +
|
|
116
|
+
`${dashUrl()} → API 密钥.`,
|
|
117
|
+
});
|
|
114
118
|
}
|
|
115
|
-
|
|
116
|
-
reporter.
|
|
117
|
-
return { token, me };
|
|
118
|
-
} finally {
|
|
119
|
-
callback.close();
|
|
119
|
+
} else {
|
|
120
|
+
reporter.warn("--no-verify: token saved without checking it. Run `collectui whoami` to verify.");
|
|
120
121
|
}
|
|
122
|
+
saveSession(token, me, { reporter });
|
|
123
|
+
reporter.outro("Login complete. Try `collectui libs`.");
|
|
124
|
+
return { token, me };
|
|
121
125
|
}
|
|
122
126
|
|
|
123
127
|
function tokenOrThrow(value) {
|
|
@@ -131,22 +135,18 @@ function tokenOrThrow(value) {
|
|
|
131
135
|
return token;
|
|
132
136
|
}
|
|
133
137
|
|
|
134
|
-
async function promptToken(
|
|
135
|
-
if (!process.stdin.isTTY || !process.stdout.isTTY) return
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
timeout,
|
|
143
|
-
]);
|
|
144
|
-
if (answer === "") return "";
|
|
145
|
-
return answer;
|
|
138
|
+
async function promptToken() {
|
|
139
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
|
|
140
|
+
const v = await p.password({
|
|
141
|
+
message: "Paste your Dash PAT (dpat_…, hidden input)",
|
|
142
|
+
mask: "*",
|
|
143
|
+
});
|
|
144
|
+
if (p.isCancel(v)) return null;
|
|
145
|
+
return String(v ?? "");
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
-
/**
|
|
149
|
-
export function startCallbackServer() {
|
|
148
|
+
/** 本地回调监听:随机 secret 路径 + 可选 state 回查(Dash /authorize 会把 state 原样带回)。 */
|
|
149
|
+
export function startCallbackServer({ state } = {}) {
|
|
150
150
|
const secret = randomBytes(12).toString("hex");
|
|
151
151
|
let resolveToken;
|
|
152
152
|
const tokenPromise = new Promise((resolve) => {
|
|
@@ -156,18 +156,17 @@ export function startCallbackServer() {
|
|
|
156
156
|
|
|
157
157
|
const server = createServer((req, res) => {
|
|
158
158
|
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
159
|
-
|
|
159
|
+
const token = url.searchParams.get("token") ?? "";
|
|
160
|
+
const gotState = url.searchParams.get("state") ?? "";
|
|
161
|
+
if (url.pathname !== `/${secret}` || (state && gotState !== state) || !token) {
|
|
160
162
|
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
161
163
|
res.end("Not found");
|
|
162
164
|
return;
|
|
163
165
|
}
|
|
164
|
-
const token = url.searchParams.get("token") ?? "";
|
|
165
166
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
166
167
|
res.end("<!doctype html><meta charset=utf-8><title>CollectUI</title><p>Token received. You can close this window.</p>");
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
resolveToken(token);
|
|
170
|
-
}
|
|
168
|
+
pending = false;
|
|
169
|
+
resolveToken(token);
|
|
171
170
|
});
|
|
172
171
|
|
|
173
172
|
const listening = new Promise((resolve, reject) => {
|
package/src/update.mjs
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { configDir } from "./config.mjs";
|
|
5
|
+
import { httpRequest } from "./http.mjs";
|
|
6
|
+
import { CLI_VERSION } from "./version.mjs";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 自更新(2026-11-30):
|
|
10
|
+
* - 启动时后台异步检查(12h 间隔 + ~/.collectui/update-check.json 缓存),绝不阻塞命令
|
|
11
|
+
* - TTY 交互下默认自动后台更新(spawn npm i -g,当前进程不受影响);headless/--json
|
|
12
|
+
* 完全不碰(Agent/CI 输出契约不可被自更新搅动)
|
|
13
|
+
* - 开关:COLLECTUI_NO_AUTO_UPDATE=1(CI 显式意图 → 全静默)或 config.autoUpdate=false
|
|
14
|
+
* (`collectui update --off` → 仍提示新版,但不自动动手);npx 临时跑不自动更
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const NPM_PACKAGE = "@collectui/cli";
|
|
18
|
+
const REGISTRY_LATEST = "https://registry.npmjs.org/@collectui/cli/latest";
|
|
19
|
+
const CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000;
|
|
20
|
+
const SPAWN_BACKOFF_MS = 24 * 60 * 60 * 1000;
|
|
21
|
+
|
|
22
|
+
function cacheFile() {
|
|
23
|
+
return join(configDir(), "update-check.json");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function readUpdateCache() {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(readFileSync(cacheFile(), "utf8"));
|
|
29
|
+
} catch {
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function writeUpdateCache(patch) {
|
|
35
|
+
try {
|
|
36
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
37
|
+
writeFileSync(cacheFile(), `${JSON.stringify({ ...readUpdateCache(), ...patch }, null, 2)}\n`, {
|
|
38
|
+
mode: 0o600,
|
|
39
|
+
});
|
|
40
|
+
} catch {
|
|
41
|
+
// 缓存写失败只影响提醒节奏,不影响功能
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 语义版本比较(忽略 -suffix):-1 / 0 / 1。 */
|
|
46
|
+
export function compareVersions(a, b) {
|
|
47
|
+
const parts = (v) =>
|
|
48
|
+
String(v)
|
|
49
|
+
.split("-")[0]
|
|
50
|
+
.split(".")
|
|
51
|
+
.map((n) => Number.parseInt(n, 10) || 0);
|
|
52
|
+
const [pa, pb] = [parts(a), parts(b)];
|
|
53
|
+
for (let i = 0; i < 3; i += 1) {
|
|
54
|
+
const x = pa[i] ?? 0;
|
|
55
|
+
const y = pb[i] ?? 0;
|
|
56
|
+
if (x !== y) return x > y ? 1 : -1;
|
|
57
|
+
}
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 纯决策函数(单测覆盖):本次启动对更新做点什么。
|
|
63
|
+
* 返回 { mode, latest?, reason },mode ∈
|
|
64
|
+
* off-silent(env 显式禁 → 全静默)| none | notify(只提示)| notify-spawn(提示+后台更)| check(到点检查)
|
|
65
|
+
*/
|
|
66
|
+
export function decideUpdate({
|
|
67
|
+
env = process.env,
|
|
68
|
+
config = {},
|
|
69
|
+
cache = {},
|
|
70
|
+
now = Date.now(),
|
|
71
|
+
isTTY = process.stdout.isTTY,
|
|
72
|
+
version = CLI_VERSION,
|
|
73
|
+
intervalMs = CHECK_INTERVAL_MS,
|
|
74
|
+
spawnBackoffMs = SPAWN_BACKOFF_MS,
|
|
75
|
+
} = {}) {
|
|
76
|
+
const noAuto = env.COLLECTUI_NO_AUTO_UPDATE;
|
|
77
|
+
if (noAuto === "1" || noAuto === "true" || noAuto === "yes") {
|
|
78
|
+
return { mode: "off-silent", reason: "env-disabled" };
|
|
79
|
+
}
|
|
80
|
+
if (String(env.npm_execpath ?? "").includes("_npx")) {
|
|
81
|
+
return { mode: "none", reason: "npx" };
|
|
82
|
+
}
|
|
83
|
+
if (!isTTY) {
|
|
84
|
+
return { mode: "none", reason: "non-tty" };
|
|
85
|
+
}
|
|
86
|
+
const autoOn = config.autoUpdate !== false;
|
|
87
|
+
const outdated = cache.latest ? compareVersions(cache.latest, version) > 0 : false;
|
|
88
|
+
if (outdated) {
|
|
89
|
+
if (!autoOn) return { mode: "notify", latest: cache.latest, reason: "manual-mode" };
|
|
90
|
+
const spawnedRecently = cache.spawnedAt && now - cache.spawnedAt < spawnBackoffMs;
|
|
91
|
+
return spawnedRecently
|
|
92
|
+
? { mode: "notify", latest: cache.latest, reason: "spawn-pending" }
|
|
93
|
+
: { mode: "notify-spawn", latest: cache.latest, reason: "cached-outdated" };
|
|
94
|
+
}
|
|
95
|
+
if (now - (cache.lastCheck ?? 0) >= intervalMs) {
|
|
96
|
+
return { mode: "check", reason: "due" };
|
|
97
|
+
}
|
|
98
|
+
return { mode: "none", reason: "recent" };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** registry latest → 版本号;失败抛错(调用方决定吞还是报)。 */
|
|
102
|
+
export async function fetchLatestVersion({ timeout = 8_000 } = {}) {
|
|
103
|
+
const out = await httpRequest(REGISTRY_LATEST, { timeout, retries: 1 });
|
|
104
|
+
if (!out.res.ok) throw new Error(`registry ${out.res.status}`);
|
|
105
|
+
const parsed = JSON.parse(out.text);
|
|
106
|
+
const v = parsed?.version;
|
|
107
|
+
if (typeof v !== "string" || !v) throw new Error("registry response has no version");
|
|
108
|
+
return v;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 后台静默 spawn npm i -g;npm 不存在返回 false。 */
|
|
112
|
+
export function spawnGlobalInstall() {
|
|
113
|
+
const probe = spawnSync("npm", ["--version"], { timeout: 10_000, encoding: "utf8" });
|
|
114
|
+
if (probe.status !== 0 || probe.error) return false;
|
|
115
|
+
const child = spawn("npm", ["install", "-g", `${NPM_PACKAGE}@latest`], {
|
|
116
|
+
detached: true,
|
|
117
|
+
stdio: "ignore",
|
|
118
|
+
shell: process.platform === "win32",
|
|
119
|
+
});
|
|
120
|
+
child.unref();
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 后台异步检查 + 视开关自动更;fire-and-forget,绝不抛。 */
|
|
125
|
+
export function backgroundCheck({ autoOn = true, reporter } = {}) {
|
|
126
|
+
const started = Date.now();
|
|
127
|
+
return fetchLatestVersion()
|
|
128
|
+
.then((latest) => {
|
|
129
|
+
writeUpdateCache({ lastCheck: started, latest });
|
|
130
|
+
if (autoOn && compareVersions(latest, CLI_VERSION) > 0) {
|
|
131
|
+
const ok = spawnGlobalInstall();
|
|
132
|
+
writeUpdateCache({ spawnedAt: Date.now(), spawnTo: ok ? latest : null });
|
|
133
|
+
if (!ok && reporter) reporter.warn(`Auto-update failed (npm not found). Run \`npm i -g ${NPM_PACKAGE}\` manually.`);
|
|
134
|
+
}
|
|
135
|
+
return latest;
|
|
136
|
+
})
|
|
137
|
+
.catch(() => undefined);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 启动钩子(cli.main 里 fire-and-forget 调):按 decideUpdate 执行提示/检查/自动更。
|
|
142
|
+
* 提示走 reporter(TTY 人类输出);headless 由 decideUpdate 的 isTTY 门挡掉。
|
|
143
|
+
*/
|
|
144
|
+
export function startBackgroundUpdate(reporter, deps = {}) {
|
|
145
|
+
const decision = decideUpdate(deps);
|
|
146
|
+
if (decision.mode === "off-silent" || decision.mode === "none") return;
|
|
147
|
+
if (decision.mode === "notify" || decision.mode === "notify-spawn") {
|
|
148
|
+
const to = decision.latest;
|
|
149
|
+
if (decision.mode === "notify-spawn") {
|
|
150
|
+
const ok = spawnGlobalInstall();
|
|
151
|
+
writeUpdateCache({ spawnedAt: Date.now(), spawnTo: ok ? to : null });
|
|
152
|
+
reporter.info(
|
|
153
|
+
ok
|
|
154
|
+
? `⬆ ${NPM_PACKAGE} ${CLI_VERSION} → ${to}: updating in background — takes effect on next run.`
|
|
155
|
+
: `⬆ ${NPM_PACKAGE} ${to} available (auto-update failed; run \`npm i -g ${NPM_PACKAGE}\`).`
|
|
156
|
+
);
|
|
157
|
+
} else {
|
|
158
|
+
reporter.info(
|
|
159
|
+
`⬆ ${NPM_PACKAGE} ${CLI_VERSION} → ${to} available. Background update was already attempted — if your version didn't change, run \`collectui update\`.`
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// mode === "check"
|
|
165
|
+
backgroundCheck({ autoOn: deps.config?.autoUpdate !== false, reporter });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 手动更新(`collectui update`):前台跑,人看着进度。runner 可注入(测试)。 */
|
|
169
|
+
export function runManualUpdate({ runner } = {}) {
|
|
170
|
+
const run = runner ?? ((args) => spawnSync("npm", args, { stdio: "inherit", shell: process.platform === "win32" }));
|
|
171
|
+
return run(["install", "-g", `${NPM_PACKAGE}@latest`]);
|
|
172
|
+
}
|