@tu-design/cli 0.4.0 → 0.4.2
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 +65 -0
- package/dist/index.mjs +521 -59
- package/dist/mcp-core-Ct8Xf-FY.mjs +70 -0
- package/package.json +7 -5
package/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# @tu-design/cli
|
|
2
|
+
|
|
3
|
+
`tu-design` —— [tu-design](../vue) 组件库的 registry 分发 CLI(shadcn 模式):初始化项目配置,并把组件源码从 registry 拉取写入你的项目。
|
|
4
|
+
|
|
5
|
+
## 使用
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx @tu-design/cli init
|
|
9
|
+
npx @tu-design/cli add button
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
### `init`
|
|
13
|
+
|
|
14
|
+
初始化 `components.json`,并自动完成基础接入:
|
|
15
|
+
|
|
16
|
+
- 写入 `components.json`(registry URL、别名等配置)
|
|
17
|
+
- 注入 `cn` 工具到 `src/lib/utils.ts`
|
|
18
|
+
- 将主题 tokens 合并进全局 CSS(自动探测常见位置,可用 `--css` 指定;已包含则跳过)
|
|
19
|
+
- 写入 `AGENTS.md` AI 协作规则(组件安装 / 自动导入 / 语义 token 主题约定,供 AI 编码代理遵循;文件已存在时不覆盖,`--no-agents` 可显式跳过)
|
|
20
|
+
- 探测包管理器并安装运行时依赖(`clsx` / `tailwind-merge` / `class-variance-authority`)
|
|
21
|
+
|
|
22
|
+
| 选项 | 说明 |
|
|
23
|
+
| ------------------ | ----------------------------------- |
|
|
24
|
+
| `--registry <url>` | registry URL,默认线上 Pages 数据源 |
|
|
25
|
+
| `--css <path>` | 全局 CSS 路径 |
|
|
26
|
+
| `--no-agents` | 不写入 AGENTS.md AI 协作规则 |
|
|
27
|
+
|
|
28
|
+
### `add <components...>`
|
|
29
|
+
|
|
30
|
+
按名字添加组件源码(支持一次多个),文件写入 `components.json` 声明的位置:
|
|
31
|
+
|
|
32
|
+
| 选项 | 说明 |
|
|
33
|
+
| ------------------ | ---------------------------------------- |
|
|
34
|
+
| `--registry <url>` | 覆盖 `components.json` 中的 registry URL |
|
|
35
|
+
| `--overwrite` | 覆盖已存在的文件而不询问 |
|
|
36
|
+
|
|
37
|
+
### `mcp`
|
|
38
|
+
|
|
39
|
+
启动 MCP Server(stdio 传输,只查询、不安装):供 Claude / Cursor 等 AI 客户端在线查询组件 registry——列出组件、按关键字搜索、获取单个组件的 registry 详情(内联源码、依赖与安装提示),引导 AI 用 CLI 安装而不是手写源码。
|
|
40
|
+
|
|
41
|
+
| 选项 | 说明 |
|
|
42
|
+
| ------------------ | ----------------- |
|
|
43
|
+
| `--registry <url>` | registry URL 通道 |
|
|
44
|
+
|
|
45
|
+
客户端配置示例(与文档站一致):
|
|
46
|
+
|
|
47
|
+
```json
|
|
48
|
+
{ "mcpServers": { "tu-design": { "command": "npx", "args": ["-y", "@tu-design/cli", "mcp"] } } }
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## 工作机制
|
|
52
|
+
|
|
53
|
+
CLI 从 registry 服务拉取每个组件的 **registry JSON**(遵循 [shadcn registry-item schema](https://ui.shadcn.com/schema/registry-item.json)),JSON 中内联了文件内容与写入目标,并声明:
|
|
54
|
+
|
|
55
|
+
- `registryDependencies` —— 依赖的基础项(如 `utils`、`tokens`),CLI 会先行安装
|
|
56
|
+
- `dependencies` —— 需要的 npm 依赖(如 Ark UI、TanStack 包),CLI 检测到后用当前包管理器安装
|
|
57
|
+
|
|
58
|
+
默认 registry 数据源是文档站 Pages 上发布的 `https://gopowerteam.github.io/tu-design/r/vue`,由 [`@tu-design/vue` 的 `generate:registry`](../vue) 生成并随 Pages 部署更新,可用 `--registry` 指向自建服务。
|
|
59
|
+
|
|
60
|
+
## 相关
|
|
61
|
+
|
|
62
|
+
- 组件库:[@tu-design/vue](../vue)
|
|
63
|
+
- 文档站:<https://gopowerteam.github.io/tu-design/>(含 CLI 指南)
|
|
64
|
+
- 仓库:<https://github.com/gopowerteam/tu-design>
|
|
65
|
+
- 许可:MIT
|
package/dist/index.mjs
CHANGED
|
@@ -4,8 +4,8 @@ import { spawnSync } from "node:child_process";
|
|
|
4
4
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import picocolors from "picocolors";
|
|
7
|
-
import { detect } from "package-manager-detector";
|
|
8
7
|
import { dirname, join } from "node:path";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
9
|
//#region src/io/node.ts
|
|
10
10
|
const nodeIo = {
|
|
11
11
|
exists: (path) => existsSync(path),
|
|
@@ -30,6 +30,20 @@ function npmItemPath(name) {
|
|
|
30
30
|
return join(dirname(pkgJson), "dist/registry/vue", `${name}.json`);
|
|
31
31
|
}
|
|
32
32
|
//#endregion
|
|
33
|
+
//#region src/lib/json.ts
|
|
34
|
+
/**
|
|
35
|
+
* 统一 JSON 解析报错:裸 SyntaxError 不含文件名,用户无从下手;这里补上来源。
|
|
36
|
+
* label 用面向用户的文件名(如 `components.json`),而不是绝对路径。
|
|
37
|
+
*/
|
|
38
|
+
function parseJson(text, label) {
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(text);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
43
|
+
throw new Error(`${label} 不是合法 JSON:${reason}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
33
47
|
//#region src/lib/config.ts
|
|
34
48
|
/** init 未显式传 --registry 时写入 components.json 的默认 URL 通道(不可达时 add 走 npm 兜底)。 */
|
|
35
49
|
const DEFAULT_REGISTRY = "https://gopowerteam.github.io/tu-design/r/vue";
|
|
@@ -75,12 +89,43 @@ function configPath(cwd) {
|
|
|
75
89
|
function loadConfig(io, cwd) {
|
|
76
90
|
const path = configPath(cwd);
|
|
77
91
|
if (!io.exists(path)) throw new Error(`未找到 ${CONFIG_FILE},请先运行 \`tu-design init\``);
|
|
78
|
-
return validateConfig(
|
|
92
|
+
return validateConfig(parseJson(io.readFile(path), CONFIG_FILE));
|
|
79
93
|
}
|
|
80
94
|
function saveConfig(io, cwd, config) {
|
|
81
95
|
io.writeFile(configPath(cwd), `${JSON.stringify(config, null, 2)}\n`);
|
|
82
96
|
}
|
|
83
97
|
//#endregion
|
|
98
|
+
//#region src/lib/ai-rules.ts
|
|
99
|
+
/**
|
|
100
|
+
* init 注入到用户项目根目录 AGENTS.md 的 AI 协作规则。
|
|
101
|
+
* 目的:让 AI 编码代理遵循 tu-design 的组件安装 / 导入 / 主题约定,
|
|
102
|
+
* 而不是手写组件源码或硬编码样式,绕开 registry 分发链路。
|
|
103
|
+
*/
|
|
104
|
+
const AGENTS_MD_SOURCE = `# tu-design AI 协作规则
|
|
105
|
+
|
|
106
|
+
本项目使用 tu-design(shadcn 风格 Vue 3 组件库),AI 协作约定如下:
|
|
107
|
+
|
|
108
|
+
## 组件安装
|
|
109
|
+
|
|
110
|
+
- 组件必须通过 CLI 安装:在项目根目录执行 \`npx @tu-design/cli add <name>\`,禁止手写组件源码。
|
|
111
|
+
- 首次接入先安装基础项:\`npx @tu-design/cli add utils tokens\`。
|
|
112
|
+
|
|
113
|
+
## 导入约定
|
|
114
|
+
|
|
115
|
+
- 组件经 unplugin-vue-components + \`TuDesignResolver\` 自动导入,模板直接写 \`<Button />\`,无需手动 import。
|
|
116
|
+
- \`cn\` 来自 \`@/lib/utils\`。
|
|
117
|
+
|
|
118
|
+
## 主题约定
|
|
119
|
+
|
|
120
|
+
- 颜色/圆角一律使用语义 token 类(\`bg-primary\`、\`text-muted-foreground\`、\`rounded-md\`),禁止硬编码十六进制色值。
|
|
121
|
+
- 暗色模式由 \`.dark\` class 驱动。
|
|
122
|
+
|
|
123
|
+
## 参考资料
|
|
124
|
+
|
|
125
|
+
- 完整组件清单:https://gopowerteam.github.io/tu-design/llms.txt(可整页抓取给 AI)
|
|
126
|
+
- 全量文档:https://gopowerteam.github.io/tu-design/llms-full.txt(可整页抓取给 AI)
|
|
127
|
+
`;
|
|
128
|
+
//#endregion
|
|
84
129
|
//#region src/lib/alias.ts
|
|
85
130
|
/**
|
|
86
131
|
* 将 paths 合并进 tsconfig 文本。优先 JSON round-trip;
|
|
@@ -159,6 +204,16 @@ function applyAliases(io, cwd, aliasRoot) {
|
|
|
159
204
|
//#endregion
|
|
160
205
|
//#region src/lib/init-core.ts
|
|
161
206
|
/**
|
|
207
|
+
* init 注入的源码(TOKENS_CSS_SOURCE / CN_UTIL_SOURCE)里出现的裸包说明符,
|
|
208
|
+
* 必须全部在此声明,否则 init 出来的项目首屏构建即失败(init-core.test.ts 强制校验)。
|
|
209
|
+
*/
|
|
210
|
+
const RUNTIME_DEPS = [
|
|
211
|
+
"clsx",
|
|
212
|
+
"tailwind-merge",
|
|
213
|
+
"class-variance-authority",
|
|
214
|
+
"tw-animate-css"
|
|
215
|
+
];
|
|
216
|
+
/**
|
|
162
217
|
* 与 @tu-design/vue/src/styles/tokens.css 保持一致(init-core.test.ts 有防漂移守卫)。
|
|
163
218
|
* 来源:packages/vue/src/styles/tokens.css
|
|
164
219
|
*/
|
|
@@ -192,6 +247,10 @@ const TOKENS_CSS_SOURCE = `@import "tw-animate-css";
|
|
|
192
247
|
--input: oklch(0.922 0 0);
|
|
193
248
|
--ring: oklch(0.708 0 0);
|
|
194
249
|
--radius: 0.625rem;
|
|
250
|
+
/* 层叠序:表体 sticky < 表头 sticky < 浮层/弹窗(同级浮层按 DOM 挂载次序叠放) */
|
|
251
|
+
--z-sticky: 10;
|
|
252
|
+
--z-sticky-head: 20;
|
|
253
|
+
--z-overlay: 50;
|
|
195
254
|
}
|
|
196
255
|
|
|
197
256
|
.dark {
|
|
@@ -307,9 +366,11 @@ function runInit(io, cwd, opts) {
|
|
|
307
366
|
const cssRel = probeCssPath(io, cwd, opts.css ?? config.tailwind.css);
|
|
308
367
|
const cssPath = joinPosix(cwd, cssRel);
|
|
309
368
|
const globalCss = io.exists(cssPath) ? io.readFile(cssPath) : "";
|
|
310
|
-
|
|
369
|
+
const pkgPath = joinPosix(cwd, "package.json");
|
|
370
|
+
if (!io.exists(pkgPath)) throw new Error(`未找到 ${pkgPath},请在 npm 项目根目录运行 \`tu-design init\``);
|
|
371
|
+
if (!detectTailwindV4(parseJson(io.readFile(pkgPath), "package.json"), globalCss)) throw new Error("未检测到 Tailwind CSS v4:需要 package.json 中的 tailwindcss ^4 依赖,以及全局 CSS 中的 @import \"tailwindcss\";");
|
|
311
372
|
const configPath = joinPosix(cwd, "components.json");
|
|
312
|
-
if (io.exists(configPath)) validateConfig(
|
|
373
|
+
if (io.exists(configPath)) validateConfig(parseJson(io.readFile(configPath), "components.json"));
|
|
313
374
|
else saveConfig(io, cwd, {
|
|
314
375
|
...config,
|
|
315
376
|
tailwind: { css: cssRel }
|
|
@@ -319,12 +380,17 @@ function runInit(io, cwd, opts) {
|
|
|
319
380
|
const merged = mergeTokensCss(globalCss, TOKENS_CSS_SOURCE);
|
|
320
381
|
const skippedCss = merged === globalCss;
|
|
321
382
|
if (!skippedCss) io.writeFile(cssPath, merged);
|
|
383
|
+
const agentsPath = joinPosix(cwd, "AGENTS.md");
|
|
384
|
+
const skippedAgents = opts.agents === false || io.exists(agentsPath);
|
|
385
|
+
if (!skippedAgents) io.writeFile(agentsPath, AGENTS_MD_SOURCE);
|
|
322
386
|
applyAliases(io, cwd, aliasRoot);
|
|
323
387
|
return {
|
|
324
388
|
configPath,
|
|
325
389
|
cnPath,
|
|
326
390
|
cssPath,
|
|
327
|
-
skippedCss
|
|
391
|
+
skippedCss,
|
|
392
|
+
agentsPath,
|
|
393
|
+
skippedAgents
|
|
328
394
|
};
|
|
329
395
|
}
|
|
330
396
|
//#endregion
|
|
@@ -334,11 +400,15 @@ const ITEM_TYPES = [
|
|
|
334
400
|
"registry:lib",
|
|
335
401
|
"registry:style"
|
|
336
402
|
];
|
|
337
|
-
/**
|
|
403
|
+
/**
|
|
404
|
+
* override(--registry)优先于 components.json。
|
|
405
|
+
* 去掉尾部 `/`:拼接处是 `${url}/${name}.json`,用户从浏览器地址栏复制带斜杠的 URL
|
|
406
|
+
* 会拼出 `//button.json`,不少静态托管据此 404。
|
|
407
|
+
*/
|
|
338
408
|
function resolveRegistryUrl(config, override) {
|
|
339
|
-
return override ?? config.registry;
|
|
409
|
+
return (override ?? config.registry).replace(/\/+$/, "");
|
|
340
410
|
}
|
|
341
|
-
/** registry item 最小结构校验(name/type/files
|
|
411
|
+
/** registry item 最小结构校验(name/type/files),files 逐文件校验形态。 */
|
|
342
412
|
function validateRegistryItem(raw) {
|
|
343
413
|
if (typeof raw !== "object" || raw === null) throw new Error("registry item 不是 JSON 对象");
|
|
344
414
|
const obj = raw;
|
|
@@ -347,18 +417,29 @@ function validateRegistryItem(raw) {
|
|
|
347
417
|
if (typeof obj.type !== "string" || !ITEM_TYPES.includes(obj.type)) missing.push("type");
|
|
348
418
|
if (!Array.isArray(obj.files)) missing.push("files");
|
|
349
419
|
if (missing.length > 0) throw new Error(`registry item 缺少字段:${missing.join("、")}`);
|
|
420
|
+
const badFile = obj.files.findIndex((f) => typeof f !== "object" || f === null || typeof f.path !== "string" || typeof f.target !== "string" || typeof f.content !== "string");
|
|
421
|
+
if (badFile !== -1) throw new Error(`registry item ${String(obj.name)} 的 files[${badFile}] 缺少 path/target/content 字符串字段`);
|
|
422
|
+
if (obj.version !== void 0 && typeof obj.version !== "string") throw new Error(`registry item ${String(obj.name)} 的 version 字段必须是字符串,得到 ${obj.version === null ? "null" : typeof obj.version}`);
|
|
350
423
|
return raw;
|
|
351
424
|
}
|
|
425
|
+
function reasonOf(error) {
|
|
426
|
+
return error instanceof Error ? error.message : String(error);
|
|
427
|
+
}
|
|
352
428
|
/**
|
|
353
429
|
* 双通道解析:URL 优先(fetch `${registryUrl}/${name}.json`),
|
|
354
|
-
* 失败 / 404 / 校验不过时回退 npm
|
|
430
|
+
* 失败 / 404 / 校验不过时回退 npm 通道;双失败抛错含组件名与 URL 通道的真实原因
|
|
431
|
+
* (吞掉原因会让用户去查 npm,问题其实出在 registry 网络或 JSON 损坏)。
|
|
355
432
|
*/
|
|
356
433
|
async function fetchItem(fetcher, registryUrl, npm, name) {
|
|
434
|
+
const url = `${registryUrl}/${name}.json`;
|
|
435
|
+
let urlFailure;
|
|
357
436
|
try {
|
|
358
|
-
return validateRegistryItem(await fetcher.fetchJson(
|
|
359
|
-
} catch {
|
|
437
|
+
return validateRegistryItem(await fetcher.fetchJson(url));
|
|
438
|
+
} catch (error) {
|
|
439
|
+
urlFailure = reasonOf(error);
|
|
440
|
+
}
|
|
360
441
|
if (npm.hasItem(name)) return validateRegistryItem(npm.readItem(name));
|
|
361
|
-
throw new Error(`无法获取组件 ${name}:URL
|
|
442
|
+
throw new Error(`无法获取组件 ${name}:URL 通道 ${url} 失败(${urlFailure}),npm 通道(@tu-design/vue)亦不可用`);
|
|
362
443
|
}
|
|
363
444
|
//#endregion
|
|
364
445
|
//#region src/lib/pm.ts
|
|
@@ -368,19 +449,33 @@ const PM_NAMES = [
|
|
|
368
449
|
"yarn",
|
|
369
450
|
"bun"
|
|
370
451
|
];
|
|
371
|
-
/** agent 形如 "pnpm@9.15.0"
|
|
372
|
-
function
|
|
373
|
-
if (!agent) return
|
|
452
|
+
/** agent 形如 "pnpm@9.15.0";未知/缺失返回 null,由调用方决定降级方式。 */
|
|
453
|
+
function parsePackageManager(agent) {
|
|
454
|
+
if (!agent) return null;
|
|
374
455
|
const name = agent.split("@")[0] ?? agent;
|
|
375
|
-
return PM_NAMES.includes(name) ? name :
|
|
456
|
+
return PM_NAMES.includes(name) ? name : null;
|
|
376
457
|
}
|
|
377
|
-
/** 由 cwd
|
|
458
|
+
/** 由 cwd 锁文件推断包管理器(纯 IO 路径,可在 memIo 下测试)。 */
|
|
378
459
|
function detectPackageManagerFromLockfiles(io, cwd) {
|
|
379
460
|
if (io.exists(`${cwd}/pnpm-lock.yaml`)) return "pnpm";
|
|
380
461
|
if (io.exists(`${cwd}/yarn.lock`)) return "yarn";
|
|
381
462
|
if (io.exists(`${cwd}/bun.lockb`) || io.exists(`${cwd}/bun.lock`)) return "bun";
|
|
382
463
|
return "npm";
|
|
383
464
|
}
|
|
465
|
+
/**
|
|
466
|
+
* 项目包管理器的唯一判定口径(init 与 add 共用,避免两条命令对同一项目给出不同答案):
|
|
467
|
+
* `packageManager` 字段(Corepack 声明的意图)优先,其次锁文件(实际使用证据),最后 npm。
|
|
468
|
+
* package.json 缺失或不可解析时静默降级——报错是 init 自己的前置校验职责。
|
|
469
|
+
*/
|
|
470
|
+
function detectPackageManagerForProject(io, cwd) {
|
|
471
|
+
const pkgPath = `${cwd}/package.json`;
|
|
472
|
+
if (io.exists(pkgPath)) try {
|
|
473
|
+
const raw = parseJson(io.readFile(pkgPath), "package.json");
|
|
474
|
+
const declared = parsePackageManager(typeof raw.packageManager === "string" ? raw.packageManager : void 0);
|
|
475
|
+
if (declared) return declared;
|
|
476
|
+
} catch {}
|
|
477
|
+
return detectPackageManagerFromLockfiles(io, cwd);
|
|
478
|
+
}
|
|
384
479
|
function buildInstallCommand(pm, deps, dev) {
|
|
385
480
|
const base = {
|
|
386
481
|
pnpm: ["pnpm", "add"],
|
|
@@ -402,6 +497,53 @@ function installDependencies(io, cwd, deps, dev, pm = detectPackageManagerFromLo
|
|
|
402
497
|
io.exec(buildInstallCommand(pm, deps, dev));
|
|
403
498
|
}
|
|
404
499
|
//#endregion
|
|
500
|
+
//#region src/lib/lockfile.ts
|
|
501
|
+
/** 组件版本记录文件,位于项目根(components.json 旁)。 */
|
|
502
|
+
const LOCKFILE_NAME = "components.lock.json";
|
|
503
|
+
function hashContent(content) {
|
|
504
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
505
|
+
}
|
|
506
|
+
/** 刻意不含 installedAt 之类时间戳字段:跨机器安装会产生 VCS diff 噪音。 */
|
|
507
|
+
function validateLockfile(raw) {
|
|
508
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(`${LOCKFILE_NAME} 内容不是 JSON 对象`);
|
|
509
|
+
const obj = raw;
|
|
510
|
+
if (obj.lockfileVersion !== 1) throw new Error(`${LOCKFILE_NAME} 的 lockfileVersion 必须是 1,得到 ${JSON.stringify(obj.lockfileVersion)}`);
|
|
511
|
+
const packages = obj.packages;
|
|
512
|
+
if (typeof packages !== "object" || packages === null || Array.isArray(packages)) throw new Error(`${LOCKFILE_NAME} 缺少 packages 对象`);
|
|
513
|
+
const out = {};
|
|
514
|
+
for (const [name, pkg] of Object.entries(packages)) {
|
|
515
|
+
if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) throw new Error(`${LOCKFILE_NAME} 的 packages.${name} 不是对象`);
|
|
516
|
+
const entry = pkg;
|
|
517
|
+
if (entry.version !== null && typeof entry.version !== "string") throw new Error(`${LOCKFILE_NAME} 的 packages.${name}.version 必须是字符串或 null,得到 ${typeof entry.version}`);
|
|
518
|
+
if (typeof entry.files !== "object" || entry.files === null || Array.isArray(entry.files)) throw new Error(`${LOCKFILE_NAME} 的 packages.${name}.files 必须是对象`);
|
|
519
|
+
const files = {};
|
|
520
|
+
for (const [path, hash] of Object.entries(entry.files)) {
|
|
521
|
+
if (typeof hash !== "string") throw new Error(`${LOCKFILE_NAME} 的 packages.${name}.files.${path} 必须是字符串,得到 ${typeof hash}`);
|
|
522
|
+
files[path] = hash;
|
|
523
|
+
}
|
|
524
|
+
out[name] = {
|
|
525
|
+
version: entry.version,
|
|
526
|
+
files
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
return {
|
|
530
|
+
lockfileVersion: 1,
|
|
531
|
+
packages: out
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
/** 文件缺失 → 空 lockfile;存在但 JSON/结构非法 → throw(损坏的 lockfile 不能静默当空处理)。 */
|
|
535
|
+
function readLockfile(io, root) {
|
|
536
|
+
const path = `${root}/${LOCKFILE_NAME}`;
|
|
537
|
+
if (!io.exists(path)) return {
|
|
538
|
+
lockfileVersion: 1,
|
|
539
|
+
packages: {}
|
|
540
|
+
};
|
|
541
|
+
return validateLockfile(parseJson(io.readFile(path), LOCKFILE_NAME));
|
|
542
|
+
}
|
|
543
|
+
function writeLockfile(io, root, lockfile) {
|
|
544
|
+
io.writeFile(`${root}/${LOCKFILE_NAME}`, `${JSON.stringify(lockfile, null, 2)}\n`);
|
|
545
|
+
}
|
|
546
|
+
//#endregion
|
|
405
547
|
//#region src/lib/write.ts
|
|
406
548
|
function parentDir(dir) {
|
|
407
549
|
if (dir === "/") return null;
|
|
@@ -418,14 +560,40 @@ function findProjectRoot(io, cwd) {
|
|
|
418
560
|
dir = up;
|
|
419
561
|
}
|
|
420
562
|
}
|
|
421
|
-
/**
|
|
563
|
+
/**
|
|
564
|
+
* registry target 恒为 POSIX /;纯逻辑层统一 POSIX 路径,真实 fs 由 node IO 兜底(Windows 同样接受 /)。
|
|
565
|
+
*
|
|
566
|
+
* target 来自远端 JSON(registry 可被任意第三方托管),必须钳在 aliasRoot 内:
|
|
567
|
+
* 绝对路径、盘符路径、或逸出 aliasRoot 的 `..` 一律拒绝,否则一个恶意/损坏的
|
|
568
|
+
* registry 项能把源码写到项目外(`~/.bashrc`、`/etc/…`)。
|
|
569
|
+
* 逐段归一后仍留在 aliasRoot 内的 `..`(如 `components/ui/../../x.ts`)允许。
|
|
570
|
+
*/
|
|
422
571
|
function resolveTarget(target, config, aliasRoot) {
|
|
423
|
-
|
|
572
|
+
const root = aliasRoot.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
573
|
+
const unix = target.replace(/\\/g, "/");
|
|
574
|
+
if (unix.startsWith("/") || /^[A-Za-z]:\//.test(unix)) throw new Error(`registry target 必须是相对路径,得到 ${target}`);
|
|
575
|
+
const segs = [];
|
|
576
|
+
for (const part of unix.split("/")) {
|
|
577
|
+
if (part === "" || part === ".") continue;
|
|
578
|
+
if (part === "..") {
|
|
579
|
+
if (segs.length === 0) throw new Error(`registry target 越出项目目录:${target}`);
|
|
580
|
+
segs.pop();
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
segs.push(part);
|
|
584
|
+
}
|
|
585
|
+
if (segs.length === 0) throw new Error(`registry target 解析后为空:${target}`);
|
|
586
|
+
return `${root}/${segs.join("/")}`;
|
|
424
587
|
}
|
|
425
588
|
function planWrites(items, io, aliasRoot, config) {
|
|
426
589
|
const plans = [];
|
|
427
590
|
for (const item of items) for (const file of item.files) {
|
|
428
|
-
|
|
591
|
+
let path;
|
|
592
|
+
try {
|
|
593
|
+
path = resolveTarget(file.target, config, aliasRoot);
|
|
594
|
+
} catch (error) {
|
|
595
|
+
throw new Error(`项 ${item.name} 的文件 ${file.path}:${error instanceof Error ? error.message : String(error)}`);
|
|
596
|
+
}
|
|
429
597
|
plans.push({
|
|
430
598
|
path,
|
|
431
599
|
content: file.content,
|
|
@@ -434,17 +602,45 @@ function planWrites(items, io, aliasRoot, config) {
|
|
|
434
602
|
}
|
|
435
603
|
return plans;
|
|
436
604
|
}
|
|
605
|
+
/**
|
|
606
|
+
* 覆盖安全语义:内容比对(sha256)优先于存在性判断——
|
|
607
|
+
* 内容相同的重复安装不算冲突,静默跳过;只有「存在且内容不同」才进入覆盖询问 / conflict 分支。
|
|
608
|
+
*/
|
|
437
609
|
async function writeFiles(plans, io, opts) {
|
|
438
|
-
const
|
|
610
|
+
const result = {
|
|
611
|
+
written: [],
|
|
612
|
+
overwrites: [],
|
|
613
|
+
upToDate: [],
|
|
614
|
+
declined: [],
|
|
615
|
+
conflicts: []
|
|
616
|
+
};
|
|
439
617
|
for (const plan of plans) {
|
|
440
|
-
if (
|
|
441
|
-
if (
|
|
442
|
-
|
|
618
|
+
if (io.exists(plan.path)) {
|
|
619
|
+
if (hashContent(io.readFile(plan.path)) === hashContent(plan.content)) {
|
|
620
|
+
result.upToDate.push(plan.path);
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
if (opts.overwrite) {
|
|
624
|
+
io.writeFile(plan.path, plan.content);
|
|
625
|
+
result.written.push(plan.path);
|
|
626
|
+
result.overwrites.push(plan.path);
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (opts.confirm) {
|
|
630
|
+
if (await opts.confirm(`文件已有本地改动,覆盖?${plan.path}`)) {
|
|
631
|
+
io.writeFile(plan.path, plan.content);
|
|
632
|
+
result.written.push(plan.path);
|
|
633
|
+
result.overwrites.push(plan.path);
|
|
634
|
+
} else result.declined.push(plan.path);
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
result.conflicts.push(plan.path);
|
|
638
|
+
continue;
|
|
443
639
|
}
|
|
444
640
|
io.writeFile(plan.path, plan.content);
|
|
445
|
-
written.push(plan.path);
|
|
641
|
+
result.written.push(plan.path);
|
|
446
642
|
}
|
|
447
|
-
return
|
|
643
|
+
return result;
|
|
448
644
|
}
|
|
449
645
|
//#endregion
|
|
450
646
|
//#region src/lib/add-core.ts
|
|
@@ -483,32 +679,142 @@ function collectDeps(items) {
|
|
|
483
679
|
devDependencies
|
|
484
680
|
};
|
|
485
681
|
}
|
|
486
|
-
|
|
682
|
+
/** add / diff 共用:由项目根推出组件源码落点根(aliasRoot)。 */
|
|
683
|
+
function aliasRootOf(root) {
|
|
684
|
+
return `${root}/src`;
|
|
685
|
+
}
|
|
487
686
|
async function runAdd(io, cwd, names, opts) {
|
|
488
687
|
const root = findProjectRoot(io, cwd);
|
|
489
688
|
const config = loadConfig(io, root);
|
|
490
689
|
const registryUrl = resolveRegistryUrl(config, opts.registry);
|
|
491
|
-
const aliasRoot =
|
|
690
|
+
const aliasRoot = aliasRootOf(root);
|
|
492
691
|
const npm = opts.npm ?? {
|
|
493
692
|
hasItem: () => false,
|
|
494
693
|
readItem: () => void 0
|
|
495
694
|
};
|
|
496
695
|
const items = await resolveTopo(names, (name) => fetchItem(io, registryUrl, npm, name));
|
|
497
|
-
const
|
|
696
|
+
const plans = planWrites(items, io, aliasRoot, config);
|
|
697
|
+
const { dependencies, devDependencies } = collectDeps(items);
|
|
698
|
+
if (opts.dryRun) {
|
|
699
|
+
const files = [];
|
|
700
|
+
const overwrites = [];
|
|
701
|
+
const upToDate = [];
|
|
702
|
+
for (const plan of plans) {
|
|
703
|
+
if (!io.exists(plan.path)) {
|
|
704
|
+
files.push(plan.path);
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
if (hashContent(io.readFile(plan.path)) === hashContent(plan.content)) upToDate.push(plan.path);
|
|
708
|
+
else {
|
|
709
|
+
files.push(plan.path);
|
|
710
|
+
overwrites.push(plan.path);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return {
|
|
714
|
+
files,
|
|
715
|
+
overwrites,
|
|
716
|
+
conflicts: [],
|
|
717
|
+
upToDate,
|
|
718
|
+
declined: [],
|
|
719
|
+
dependencies,
|
|
720
|
+
devDependencies,
|
|
721
|
+
dryRun: true
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
const result = await writeFiles(plans, io, {
|
|
498
725
|
overwrite: opts.overwrite,
|
|
499
726
|
confirm: opts.confirm
|
|
500
727
|
});
|
|
501
|
-
const
|
|
502
|
-
const
|
|
728
|
+
const lockfile = readLockfile(io, root);
|
|
729
|
+
const knownRemote = /* @__PURE__ */ new Set([...result.written, ...result.upToDate]);
|
|
730
|
+
for (const item of items) {
|
|
731
|
+
const files = {};
|
|
732
|
+
let allKnown = true;
|
|
733
|
+
for (const file of item.files) {
|
|
734
|
+
const target = resolveTarget(file.target, config, aliasRoot);
|
|
735
|
+
if (!knownRemote.has(target)) {
|
|
736
|
+
allKnown = false;
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
files[target] = hashContent(file.content);
|
|
740
|
+
}
|
|
741
|
+
if (allKnown) lockfile.packages[item.name] = {
|
|
742
|
+
version: item.version ?? null,
|
|
743
|
+
files
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
writeLockfile(io, root, lockfile);
|
|
747
|
+
const pm = detectPackageManagerForProject(io, root);
|
|
503
748
|
if (dependencies.length > 0) installDependencies(io, root, dependencies, false, pm);
|
|
504
749
|
if (devDependencies.length > 0) installDependencies(io, root, devDependencies, true, pm);
|
|
505
750
|
return {
|
|
506
|
-
files,
|
|
751
|
+
files: result.written,
|
|
752
|
+
overwrites: result.overwrites,
|
|
753
|
+
conflicts: result.conflicts,
|
|
754
|
+
upToDate: result.upToDate,
|
|
755
|
+
declined: result.declined,
|
|
507
756
|
dependencies,
|
|
508
757
|
devDependencies
|
|
509
758
|
};
|
|
510
759
|
}
|
|
511
760
|
//#endregion
|
|
761
|
+
//#region src/lib/diff-core.ts
|
|
762
|
+
/**
|
|
763
|
+
* 本地文件 vs 线上 registry vs lockfile 安装时快照的三方比对。
|
|
764
|
+
* 每文件按有序决策树判定(first-match):
|
|
765
|
+
* 1. 本地 === 线上 → up-to-date
|
|
766
|
+
* 2. 无安装记录(legacy)且与线上不同 → different(两方对比降级)
|
|
767
|
+
* 3. 本地 === 上次安装 → updatable(本地干净,可安全覆盖)
|
|
768
|
+
* 4. 线上 === 上次安装 → modified(远端没动,本地改的)
|
|
769
|
+
* 5. 三方互不相同 → conflict
|
|
770
|
+
*/
|
|
771
|
+
async function diffComponents(io, fetcher, registryUrl, npm, root, config, names) {
|
|
772
|
+
const lockfile = readLockfile(io, root);
|
|
773
|
+
const list = names ?? Object.keys(lockfile.packages);
|
|
774
|
+
const aliasRoot = aliasRootOf(root);
|
|
775
|
+
const out = [];
|
|
776
|
+
for (const name of list) {
|
|
777
|
+
const record = lockfile.packages[name] ?? null;
|
|
778
|
+
const diff = {
|
|
779
|
+
name,
|
|
780
|
+
remoteVersion: null,
|
|
781
|
+
localVersion: record?.version ?? null,
|
|
782
|
+
legacy: record === null,
|
|
783
|
+
files: []
|
|
784
|
+
};
|
|
785
|
+
let item;
|
|
786
|
+
try {
|
|
787
|
+
item = await fetchItem(fetcher, registryUrl, npm, name);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
diff.error = error instanceof Error ? error.message : String(error);
|
|
790
|
+
out.push(diff);
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
diff.remoteVersion = item.version ?? null;
|
|
794
|
+
for (const file of item.files) {
|
|
795
|
+
const target = resolveTarget(file.target, config, aliasRoot);
|
|
796
|
+
const remoteHash = hashContent(file.content);
|
|
797
|
+
const installedHash = record?.files[target] ?? null;
|
|
798
|
+
let status;
|
|
799
|
+
if (!io.exists(target)) status = "missing";
|
|
800
|
+
else {
|
|
801
|
+
const localHash = hashContent(io.readFile(target));
|
|
802
|
+
if (localHash === remoteHash) status = "up-to-date";
|
|
803
|
+
else if (installedHash === null) status = "different";
|
|
804
|
+
else if (localHash === installedHash) status = "updatable";
|
|
805
|
+
else if (remoteHash === installedHash) status = "modified";
|
|
806
|
+
else status = "conflict";
|
|
807
|
+
}
|
|
808
|
+
diff.files.push({
|
|
809
|
+
target,
|
|
810
|
+
status
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
out.push(diff);
|
|
814
|
+
}
|
|
815
|
+
return out;
|
|
816
|
+
}
|
|
817
|
+
//#endregion
|
|
512
818
|
//#region src/lib/version.ts
|
|
513
819
|
/** 从 package.json 原始文本解析版本号(纯函数,便于测试)。 */
|
|
514
820
|
function parsePkgVersion(raw) {
|
|
@@ -518,35 +824,38 @@ function parsePkgVersion(raw) {
|
|
|
518
824
|
}
|
|
519
825
|
//#endregion
|
|
520
826
|
//#region src/index.ts
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
827
|
+
/** 唯一的子进程执行实现:init / add 都走它,失败原因由 stdio 直接透传给用户。 */
|
|
828
|
+
function execIn(cwd) {
|
|
829
|
+
return (cmd) => {
|
|
830
|
+
if (spawnSync(cmd[0], cmd.slice(1), {
|
|
831
|
+
cwd,
|
|
832
|
+
stdio: "inherit"
|
|
833
|
+
}).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
|
|
834
|
+
};
|
|
835
|
+
}
|
|
526
836
|
function makeExecIo(cwd) {
|
|
527
837
|
return {
|
|
528
838
|
...nodeIo,
|
|
529
|
-
exec(
|
|
530
|
-
if (spawnSync(cmd[0], cmd.slice(1), {
|
|
531
|
-
cwd,
|
|
532
|
-
stdio: "inherit"
|
|
533
|
-
}).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
|
|
534
|
-
}
|
|
839
|
+
exec: execIn(cwd)
|
|
535
840
|
};
|
|
536
841
|
}
|
|
537
842
|
const program = new Command();
|
|
538
|
-
|
|
539
|
-
program.
|
|
843
|
+
const PKG_VERSION = parsePkgVersion(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
844
|
+
program.name("tu-design").description("tu-design 组件 registry CLI").version(PKG_VERSION);
|
|
845
|
+
program.command("init").description("初始化 components.json 并注入基础依赖与样式 tokens").option("--registry <url>", "registry URL 通道", DEFAULT_REGISTRY).option("--css <path>", "全局 CSS 路径(默认自动探测常见位置)").option("--no-agents", "不写入 AGENTS.md AI 协作规则").action(async (opts) => {
|
|
540
846
|
const cwd = process.cwd();
|
|
541
847
|
try {
|
|
542
848
|
const summary = runInit(nodeIo, cwd, {
|
|
543
849
|
registry: opts.registry,
|
|
544
|
-
css: opts.css
|
|
850
|
+
css: opts.css,
|
|
851
|
+
agents: opts.agents
|
|
545
852
|
});
|
|
546
853
|
console.log(`✔ 已写入 ${summary.configPath}`);
|
|
547
854
|
console.log(`✔ 已注入 cn 工具 ${summary.cnPath}`);
|
|
548
855
|
console.log(summary.skippedCss ? `ℹ ${summary.cssPath} 已包含 tokens,跳过` : `✔ 已合并 tokens 至 ${summary.cssPath}`);
|
|
549
|
-
|
|
856
|
+
if (summary.skippedAgents) console.log(opts.agents === false ? "ℹ 已按 --no-agents 跳过 AGENTS.md" : "ℹ AGENTS.md 已存在,跳过");
|
|
857
|
+
else console.log("✔ 已写入 AGENTS.md(AI 协作规则)");
|
|
858
|
+
const pm = detectPackageManagerForProject(nodeIo, cwd);
|
|
550
859
|
console.log(`ℹ 使用 ${pm} 安装 ${RUNTIME_DEPS.join(" ")}`);
|
|
551
860
|
installDependencies(makeExecIo(cwd), cwd, RUNTIME_DEPS, false, pm);
|
|
552
861
|
console.log("✔ 依赖安装完成");
|
|
@@ -555,7 +864,7 @@ program.command("init").description("初始化 components.json 并注入基础
|
|
|
555
864
|
process.exitCode = 1;
|
|
556
865
|
}
|
|
557
866
|
});
|
|
558
|
-
program.command("add <components...>").description("添加组件源码到项目").option("--registry <url>", "覆盖 components.json 中的 registry URL").option("--overwrite", "覆盖已存在的文件而不询问").action(async (components, opts) => {
|
|
867
|
+
program.command("add <components...>").description("添加组件源码到项目").option("--registry <url>", "覆盖 components.json 中的 registry URL").option("--overwrite", "覆盖已存在的文件而不询问").option("--dry-run", "预览模式:报告将写入/覆盖/已最新的文件,不实际写入").action(async (components, opts) => {
|
|
559
868
|
const cwd = process.cwd();
|
|
560
869
|
try {
|
|
561
870
|
const summary = await runAdd({
|
|
@@ -565,18 +874,13 @@ program.command("add <components...>").description("添加组件源码到项目"
|
|
|
565
874
|
if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
|
|
566
875
|
return res.json();
|
|
567
876
|
},
|
|
568
|
-
exec(
|
|
569
|
-
if (spawnSync(cmd[0], cmd.slice(1), {
|
|
570
|
-
cwd,
|
|
571
|
-
stdio: "inherit"
|
|
572
|
-
}).status !== 0) throw new Error(`命令执行失败:${cmd.join(" ")}`);
|
|
573
|
-
}
|
|
877
|
+
exec: execIn(cwd)
|
|
574
878
|
}, cwd, components, {
|
|
575
879
|
registry: opts.registry,
|
|
576
880
|
overwrite: opts.overwrite,
|
|
881
|
+
dryRun: opts.dryRun,
|
|
577
882
|
npm: nodeNpmChannel,
|
|
578
|
-
confirm: async (msg) => {
|
|
579
|
-
if (!process.stdin.isTTY) return false;
|
|
883
|
+
confirm: process.stdin.isTTY ? async (msg) => {
|
|
580
884
|
const { default: prompts } = await import("prompts");
|
|
581
885
|
return (await prompts({
|
|
582
886
|
type: "confirm",
|
|
@@ -584,12 +888,44 @@ program.command("add <components...>").description("添加组件源码到项目"
|
|
|
584
888
|
message: msg,
|
|
585
889
|
initial: false
|
|
586
890
|
})).ok === true;
|
|
587
|
-
}
|
|
891
|
+
} : void 0
|
|
588
892
|
});
|
|
893
|
+
if (summary.dryRun) {
|
|
894
|
+
console.log("ℹ dry-run:未写入任何文件");
|
|
895
|
+
const fresh = summary.files.filter((f) => !summary.overwrites.includes(f));
|
|
896
|
+
if (fresh.length > 0) {
|
|
897
|
+
console.log("将写入:");
|
|
898
|
+
for (const f of fresh) console.log(` ${f}`);
|
|
899
|
+
}
|
|
900
|
+
if (summary.overwrites.length > 0) {
|
|
901
|
+
console.log("将覆盖:");
|
|
902
|
+
for (const f of summary.overwrites) console.log(` ${f}`);
|
|
903
|
+
}
|
|
904
|
+
if (summary.upToDate.length > 0) {
|
|
905
|
+
console.log("已最新(跳过):");
|
|
906
|
+
for (const f of summary.upToDate) console.log(` ${f}`);
|
|
907
|
+
}
|
|
908
|
+
const willInstall = [...summary.dependencies, ...summary.devDependencies];
|
|
909
|
+
if (willInstall.length > 0) console.log(`ℹ 将安装依赖(dry-run 未执行):${willInstall.join(" ")}`);
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
589
912
|
if (summary.files.length > 0) {
|
|
590
913
|
console.log("✔ 写入文件:");
|
|
591
914
|
for (const f of summary.files) console.log(` ${f}`);
|
|
592
|
-
} else console.log("ℹ
|
|
915
|
+
} else console.log("ℹ 没有写入任何文件(可能已最新或全部跳过)");
|
|
916
|
+
if (summary.upToDate.length > 0) {
|
|
917
|
+
console.log("ℹ 已是最新(跳过):");
|
|
918
|
+
for (const f of summary.upToDate) console.log(` ${f}`);
|
|
919
|
+
}
|
|
920
|
+
if (summary.declined.length > 0) {
|
|
921
|
+
console.log("ℹ 已拒绝覆盖:");
|
|
922
|
+
for (const f of summary.declined) console.log(` ${f}`);
|
|
923
|
+
}
|
|
924
|
+
if (summary.conflicts.length > 0) {
|
|
925
|
+
console.log(picocolors.yellow(`⚠ ${summary.conflicts.length} 个文件本地有改动且未覆盖;非交互环境如需覆盖请加 --overwrite`));
|
|
926
|
+
for (const f of summary.conflicts) console.log(picocolors.yellow(` ${f}`));
|
|
927
|
+
process.exitCode = 1;
|
|
928
|
+
}
|
|
593
929
|
for (const d of summary.dependencies) console.log(`✔ 依赖 ${picocolors.cyan(d)}`);
|
|
594
930
|
for (const d of summary.devDependencies) console.log(`✔ 开发依赖 ${picocolors.cyan(d)}`);
|
|
595
931
|
} catch (error) {
|
|
@@ -597,6 +933,132 @@ program.command("add <components...>").description("添加组件源码到项目"
|
|
|
597
933
|
process.exitCode = 1;
|
|
598
934
|
}
|
|
599
935
|
});
|
|
936
|
+
/** diff 状态的中文标签(展示层职责,纯逻辑层只产英文枚举)。 */
|
|
937
|
+
const DIFF_STATUS_LABELS = {
|
|
938
|
+
"up-to-date": "最新",
|
|
939
|
+
updatable: "可更新",
|
|
940
|
+
modified: "本地已改",
|
|
941
|
+
conflict: "冲突",
|
|
942
|
+
missing: "缺失",
|
|
943
|
+
different: "不一致(未跟踪)"
|
|
944
|
+
};
|
|
945
|
+
program.command("diff [components...]").description("比对本地组件与线上 registry(无参数时比对 components.lock.json 记录的全部组件)").option("--registry <url>", "覆盖 components.json 中的 registry URL").action(async (components, opts) => {
|
|
946
|
+
const cwd = process.cwd();
|
|
947
|
+
try {
|
|
948
|
+
const diffIo = {
|
|
949
|
+
...nodeIo,
|
|
950
|
+
async fetchJson(url) {
|
|
951
|
+
const res = await fetch(url);
|
|
952
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
|
|
953
|
+
return res.json();
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
const root = findProjectRoot(nodeIo, cwd);
|
|
957
|
+
const config = loadConfig(nodeIo, root);
|
|
958
|
+
const registryUrl = resolveRegistryUrl(config, opts.registry);
|
|
959
|
+
const names = components && components.length > 0 ? components : void 0;
|
|
960
|
+
const diffs = await diffComponents(diffIo, diffIo, registryUrl, nodeNpmChannel, root, config, names);
|
|
961
|
+
if (diffs.length === 0) {
|
|
962
|
+
console.log("ℹ 没有可比对的组件(components.lock.json 不存在或为空;可指定组件名)");
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
const counts = /* @__PURE__ */ new Map();
|
|
966
|
+
for (const d of diffs) {
|
|
967
|
+
const localPart = d.legacy ? "本地未跟踪(legacy)" : `本地 ${d.localVersion ?? "-"}`;
|
|
968
|
+
console.log(`▸ ${d.name}(线上 ${d.remoteVersion ?? "-"} / ${localPart})`);
|
|
969
|
+
for (const f of d.files) {
|
|
970
|
+
console.log(` ${DIFF_STATUS_LABELS[f.status]} ${f.target}`);
|
|
971
|
+
counts.set(f.status, (counts.get(f.status) ?? 0) + 1);
|
|
972
|
+
}
|
|
973
|
+
if (d.error !== void 0) console.log(picocolors.yellow(` ⚠ 获取失败:${d.error}`));
|
|
974
|
+
}
|
|
975
|
+
const stat = Object.keys(DIFF_STATUS_LABELS).filter((s) => (counts.get(s) ?? 0) > 0).map((s) => `${DIFF_STATUS_LABELS[s]} ${counts.get(s)}`).join(",");
|
|
976
|
+
if (stat.length > 0) console.log(`ℹ 统计:${stat}`);
|
|
977
|
+
const affected = diffs.filter((d) => d.files.some((f) => f.status === "updatable" || f.status === "conflict" || f.status === "missing")).map((d) => d.name);
|
|
978
|
+
if (affected.length > 0) console.log(`ℹ 更新:npx @tu-design/cli add ${affected.join(" ")} --overwrite`);
|
|
979
|
+
if ((counts.get("conflict") ?? 0) > 0) console.log(picocolors.yellow("⚠ 冲突文件:本地、上次安装、线上三者互不相同,建议先 git diff 人工比对再覆盖"));
|
|
980
|
+
} catch (error) {
|
|
981
|
+
console.error(picocolors.red(`✖ ${error instanceof Error ? error.message : String(error)}`));
|
|
982
|
+
process.exitCode = 1;
|
|
983
|
+
}
|
|
984
|
+
});
|
|
985
|
+
/** MCP 错误统一转 isError 结果(stdout 只承载 JSON-RPC,消息文本放 content)。 */
|
|
986
|
+
function mcpError(error) {
|
|
987
|
+
return {
|
|
988
|
+
isError: true,
|
|
989
|
+
content: [{
|
|
990
|
+
type: "text",
|
|
991
|
+
text: error instanceof Error ? error.message : String(error)
|
|
992
|
+
}]
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
function registryHttpFetcher() {
|
|
996
|
+
return { async fetchJson(url) {
|
|
997
|
+
const res = await fetch(url);
|
|
998
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`);
|
|
999
|
+
return res.json();
|
|
1000
|
+
} };
|
|
1001
|
+
}
|
|
1002
|
+
program.command("mcp").description("启动 MCP Server(stdio,仅查询组件 registry)").option("--registry <url>", "registry URL 通道", DEFAULT_REGISTRY).action(async (opts) => {
|
|
1003
|
+
const log = (msg) => console.error(msg);
|
|
1004
|
+
try {
|
|
1005
|
+
const [{ McpServer }, { StdioServerTransport }, { z }, { fetchRegistryIndex, searchComponents, getComponent }] = await Promise.all([
|
|
1006
|
+
import("@modelcontextprotocol/sdk/server/mcp.js"),
|
|
1007
|
+
import("@modelcontextprotocol/sdk/server/stdio.js"),
|
|
1008
|
+
import("zod"),
|
|
1009
|
+
import("./mcp-core-Ct8Xf-FY.mjs")
|
|
1010
|
+
]);
|
|
1011
|
+
const fetcher = registryHttpFetcher();
|
|
1012
|
+
const server = new McpServer({
|
|
1013
|
+
name: "tu-design",
|
|
1014
|
+
version: PKG_VERSION
|
|
1015
|
+
});
|
|
1016
|
+
server.registerTool("list_components", { description: "列出全部 tu-design 组件(name / title / description)" }, async () => {
|
|
1017
|
+
try {
|
|
1018
|
+
const list = await fetchRegistryIndex(fetcher, opts.registry);
|
|
1019
|
+
return { content: [{
|
|
1020
|
+
type: "text",
|
|
1021
|
+
text: JSON.stringify(list, null, 2)
|
|
1022
|
+
}] };
|
|
1023
|
+
} catch (error) {
|
|
1024
|
+
return mcpError(error);
|
|
1025
|
+
}
|
|
1026
|
+
});
|
|
1027
|
+
server.registerTool("search_components", {
|
|
1028
|
+
description: "按关键字搜索 tu-design 组件(大小写不敏感,匹配 name / title / description)",
|
|
1029
|
+
inputSchema: { query: z.string().describe("搜索关键字,如 table、dialog、表格") }
|
|
1030
|
+
}, async ({ query }) => {
|
|
1031
|
+
try {
|
|
1032
|
+
const results = await searchComponents(fetcher, opts.registry, query);
|
|
1033
|
+
return { content: [{
|
|
1034
|
+
type: "text",
|
|
1035
|
+
text: JSON.stringify(results, null, 2)
|
|
1036
|
+
}] };
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
return mcpError(error);
|
|
1039
|
+
}
|
|
1040
|
+
});
|
|
1041
|
+
server.registerTool("get_component", {
|
|
1042
|
+
description: "获取单个 tu-design 组件的 registry 详情(内联源码 files、依赖、安装提示);只查询,不安装",
|
|
1043
|
+
inputSchema: { name: z.string().describe("组件名,小写字母/数字/连字符,如 button") }
|
|
1044
|
+
}, async ({ name }) => {
|
|
1045
|
+
try {
|
|
1046
|
+
const item = await getComponent(fetcher, opts.registry, name);
|
|
1047
|
+
return { content: [{
|
|
1048
|
+
type: "text",
|
|
1049
|
+
text: JSON.stringify(item, null, 2)
|
|
1050
|
+
}] };
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
return mcpError(error);
|
|
1053
|
+
}
|
|
1054
|
+
});
|
|
1055
|
+
await server.connect(new StdioServerTransport());
|
|
1056
|
+
log("tu-design MCP server 运行中(stdio)");
|
|
1057
|
+
} catch (error) {
|
|
1058
|
+
log(`✖ ${error instanceof Error ? error.message : String(error)}`);
|
|
1059
|
+
process.exitCode = 1;
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
600
1062
|
program.parse();
|
|
601
1063
|
//#endregion
|
|
602
|
-
export {};
|
|
1064
|
+
export { validateRegistryItem as t };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { t as validateRegistryItem } from "./index.mjs";
|
|
2
|
+
//#region src/lib/mcp-core.ts
|
|
3
|
+
/** 组件名只允许小写字母、数字与连字符:防路径穿越与 URL 注入。 */
|
|
4
|
+
const NAME_RE = /^[a-z0-9-]+$/;
|
|
5
|
+
/** registry URL 尾斜杠会让拼接变成 //name.json,多数静态托管据此 404。 */
|
|
6
|
+
function trimUrl(registryUrl) {
|
|
7
|
+
return registryUrl.replace(/\/+$/, "");
|
|
8
|
+
}
|
|
9
|
+
function reasonOf(error) {
|
|
10
|
+
return error instanceof Error ? error.message : String(error);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* 拉取 registry 索引(GET `${registryUrl}/registry.json`),过滤只留 registry:ui 组件。
|
|
14
|
+
* 最小形态校验:items 为数组、每项 name 为 string;错误消息中文且含 URL,便于定位数据源问题。
|
|
15
|
+
*/
|
|
16
|
+
async function fetchRegistryIndex(fetcher, registryUrl) {
|
|
17
|
+
const url = `${trimUrl(registryUrl)}/registry.json`;
|
|
18
|
+
const raw = await fetcher.fetchJson(url);
|
|
19
|
+
if (typeof raw !== "object" || raw === null) throw new Error(`registry index 不是 JSON 对象:${url}`);
|
|
20
|
+
const items = raw.items;
|
|
21
|
+
if (!Array.isArray(items)) throw new Error(`registry index 缺少 items 数组:${url}`);
|
|
22
|
+
return items.map((item, index) => {
|
|
23
|
+
if (typeof item !== "object" || item === null || typeof item.name !== "string") throw new Error(`registry index items[${index}] 缺少 name 字符串字段:${url}`);
|
|
24
|
+
const obj = item;
|
|
25
|
+
return {
|
|
26
|
+
name: obj.name,
|
|
27
|
+
type: obj.type,
|
|
28
|
+
title: obj.title,
|
|
29
|
+
description: obj.description
|
|
30
|
+
};
|
|
31
|
+
}).filter((item) => item.type === "registry:ui").map((item) => ({
|
|
32
|
+
name: item.name,
|
|
33
|
+
title: typeof item.title === "string" ? item.title : "",
|
|
34
|
+
description: typeof item.description === "string" ? item.description : ""
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
/** 在 name / title / description 上做大小写不敏感子串过滤(空 query 返回全部)。 */
|
|
38
|
+
async function searchComponents(fetcher, registryUrl, query) {
|
|
39
|
+
const entries = await fetchRegistryIndex(fetcher, registryUrl);
|
|
40
|
+
const q = query.toLowerCase();
|
|
41
|
+
return entries.filter((e) => e.name.toLowerCase().includes(q) || e.title.toLowerCase().includes(q) || e.description.toLowerCase().includes(q));
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 拉取单个组件 registry item(GET `${registryUrl}/${name}.json`)。
|
|
45
|
+
* 只走线上 URL 通道并复用 validateRegistryItem 校验,不用 fetchItem 的 npm 回退——
|
|
46
|
+
* MCP 是只读查询面,npm 本地回退会让查询结果取决于安装缓存,语义混乱。
|
|
47
|
+
* 返回项附加 installHint,引导 AI 用 CLI 安装而不是复制源码。
|
|
48
|
+
*/
|
|
49
|
+
async function getComponent(fetcher, registryUrl, name) {
|
|
50
|
+
if (!NAME_RE.test(name)) throw new Error(`非法组件名 ${name}:只允许小写字母、数字与连字符`);
|
|
51
|
+
const url = `${trimUrl(registryUrl)}/${name}.json`;
|
|
52
|
+
let raw;
|
|
53
|
+
try {
|
|
54
|
+
raw = await fetcher.fetchJson(url);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new Error(`无法获取组件 ${name}:${url} 拉取失败(${reasonOf(error)})`);
|
|
57
|
+
}
|
|
58
|
+
let item;
|
|
59
|
+
try {
|
|
60
|
+
item = validateRegistryItem(raw);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
throw new Error(`组件 ${name} 的 registry item 校验失败:${url}(${reasonOf(error)})`);
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
...item,
|
|
66
|
+
installHint: `npx @tu-design/cli add ${item.name}`
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
export { fetchRegistryIndex, getComponent, searchComponents };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tu-design/cli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "tu-design CLI:初始化并按 registry 分发组件源码到用户项目(shadcn 模式)。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"tu-design": "./dist/index.mjs"
|
|
23
23
|
},
|
|
24
24
|
"files": [
|
|
25
|
-
"dist"
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md"
|
|
26
27
|
],
|
|
27
28
|
"type": "module",
|
|
28
29
|
"exports": {
|
|
@@ -33,11 +34,12 @@
|
|
|
33
34
|
"access": "public"
|
|
34
35
|
},
|
|
35
36
|
"dependencies": {
|
|
36
|
-
"@
|
|
37
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
38
|
+
"@tu-design/vue": "0.4.2",
|
|
37
39
|
"commander": "^15",
|
|
38
|
-
"package-manager-detector": "^1",
|
|
39
40
|
"picocolors": "^1",
|
|
40
|
-
"prompts": "^2"
|
|
41
|
+
"prompts": "^2",
|
|
42
|
+
"zod": "^4"
|
|
41
43
|
},
|
|
42
44
|
"devDependencies": {
|
|
43
45
|
"@types/prompts": "^2.4.8",
|