dsh-skill-browser 2.0.2 → 2.0.14

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/lib/market.js ADDED
@@ -0,0 +1,570 @@
1
+ // dsh-skill-browser - MCP 市场子模块(宿主端,v2.0.6)
2
+ //
3
+ // 数据源:官方 MCP Registry(https://registry.modelcontextprotocol.io/v0/servers)
4
+ // - 分页拉取,limit 上限 100(超出会 422),最多 30 页(契约:拉全量直到 nextCursor 为 null 或 30 页)
5
+ // - 返回原始 servers[] 数组(每项是外层 {server:{...}} 对象),原样返回不作加工
6
+ // - Registry 没有 category / tags / price 字段 → 分类与「免费」标注全部自算
7
+ //
8
+ // 磁盘缓存:~/.dsh/data/dsh-skill-browser/market.json,有效期 24 小时,
9
+ // 缓存里直接存「算好的最终 market 返回体」,避免每次都重拉重算分类。
10
+ // 网络失败且有旧缓存 → 用旧缓存并标 stale:true + warn;两者皆无 → 只回精选 + stale:true + warn。
11
+ //
12
+ // 零 npm 依赖:只用 Node 内置模块 + 全局 fetch(Node 18+,宿主 Node 均满足)。
13
+ // 所有注释与面向用户文案一律中文(简体),代码标识符英文。
14
+
15
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from "node:fs";
16
+ import { join, dirname } from "node:path";
17
+ import { fileURLToPath } from "url";
18
+ import { homedir, tmpdir } from "node:os";
19
+ // 子模块版本传播:宿主热重载时 index.js 以 ?v=<ts> 重新导入本文件,
20
+ // import.meta.url 上带同一 query,必须原样传给子模块,否则会命中 ESM registry
21
+ // 里启动时缓存的旧实例(旧 mcp.js 没有 dataDir 导出 → 链接期 SyntaxError → 热重载静默失败)。
22
+ var RELOAD_V = new URL(import.meta.url).search || "";
23
+ var mcpMod = await import("./mcp.js" + RELOAD_V);
24
+ var dataDir = mcpMod.dataDir;
25
+
26
+ // ─────────────────────────── 常量 ───────────────────────────
27
+
28
+ var REGISTRY_BASE = "https://registry.modelcontextprotocol.io/v0/servers";
29
+ var PAGE_LIMIT = 100;
30
+ var MAX_PAGES = 30;
31
+ var FETCH_TIMEOUT_MS = 20000;
32
+ var CACHE_TTL_MS = 24 * 3600 * 1000;
33
+
34
+ var DEFAULT_NODE_EXE = "C:\\Program Files\\nodejs\\node.exe";
35
+ var DEFAULT_NPX_CLI = "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npx-cli.js";
36
+ var DEFAULT_UVX = "C:\\Users\\Administrator\\.local\\bin\\uvx.exe";
37
+
38
+ // ─────────────────────────── 19 大类定义(契约严格指定 id/label/icon) ───────────────────────────
39
+ // 每条挂一组分类关键词(中英都覆盖);打分 = 命中词长,长词优先,
40
+ // 避免「web / 其他」这类宽词把别的类吃掉。
41
+
42
+ export var MARKET_CATS = [
43
+ { id: "filesystem", label: "文件系统", icon: "📁",
44
+ keywords: ["filesystem", "file system", "file manager", "directory", "folder", "文件系统", "文件系统访问", "文件", "目录", "文件夹"] },
45
+ { id: "database", label: "数据库", icon: "🗄️",
46
+ keywords: ["postgres", "postgresql", "mysql", "sqlite", "duckdb", "mongodb", "redis", "surreal", "kafka", "trino", "clickhouse", "timescale", "database", "sql", "数据仓库", "数据库", "数据存储", "查询语言", "graphql 数据"] },
47
+ { id: "devtools", label: "开发工具", icon: "🛠️",
48
+ keywords: ["developer tools", "completion", "compiler", "linter", "debugger", "code completion", "autocomplete", "ide", "sdk", "api client", "doxygen", "gitignore", "开发工具", "代码补全", "编译", "调试", "接口调试"] },
49
+ { id: "web", label: "网页与搜索", icon: "🌐",
50
+ keywords: ["web search", "search engine", "crawler", "scraper", "crawl", "scrape", "fetch", "rss", "url", "http request", "web scraping", "网页搜索", "搜索引擎", "抓取", "爬取", "网页"] },
51
+ { id: "browser", label: "浏览器自动化", icon: "🎭",
52
+ keywords: ["browser", "chrome", "chromium", "playwright", "puppeteer", "selenium", "webdriver", "browser automation", "浏览器自动化", "浏览器", "无头浏览器"] },
53
+ { id: "git", label: "代码仓库", icon: "🔗",
54
+ keywords: ["github", "gitlab", "bitbucket", "git repository", "pull request", "commit", "gitee", "代码仓库", "版本控制", "仓库", "git"] },
55
+ { id: "docs", label: "文档与办公", icon: "📄",
56
+ keywords: ["document", "pdf", "word", "excel", "spreadsheet", "notion", "confluence", "office", "workspace", "presentation", "docs", "文档", "办公", "表格", "演示文稿", "电子表格", "pdf 处理"] },
57
+ { id: "cloud", label: "云服务与部署", icon: "☁️",
58
+ keywords: ["kubernetes", "aws", "azure", "google cloud", "gcp", "docker", "terraform", "deploy", "cloudflare", "serverless", "lambda", "s3", "云服务", "云计算", "部署", "容器", "Kubernetes"] },
59
+ { id: "comms", label: "通信与邮件", icon: "💬",
60
+ keywords: ["send email", "smtp", "slack", "discord", "telegram", "whatsapp", "wechat", "message", "imap", "outlook", "gsuite", "通信", "邮件", "发送邮件", "短信", "聊天", "消息"] },
61
+ { id: "media", label: "图像与多媒体", icon: "🎨",
62
+ keywords: ["image", "video", "audio", "music", "ffmpeg", "screenshot", "photo", "media", "图像", "图片", "视频", "音频", "音乐", "截图", "多媒体"] },
63
+ { id: "memory", label: "知识与记忆", icon: "🧠",
64
+ keywords: ["memory", "knowledge", "knowledge base", "knowledge graph", "semantic", "vector", "embeddings", "rag", "知识库", "知识图谱", "记忆", "向量", "语义", "知识管理"] },
65
+ { id: "automation", label: "任务与自动化", icon: "⚙️",
66
+ keywords: ["automation", "workflow", "scheduler", "cron", "task", "orchestration", "zapier", "n8n", "自动化", "工作流", "定时任务", "任务编排", "schedule"] },
67
+ { id: "ai", label: "AI 与智能体", icon: "🤖",
68
+ keywords: ["artificial intelligence", "large language", "llm", "openai", "anthropic", "claude", "gpt", "agent", "inference", "model serving", "人工智能", "大模型", "智能体", "对话", "推理", "llm"] },
69
+ { id: "finance", label: "金融与交易", icon: "💰",
70
+ keywords: ["finance", "payment", "bank", "invoice", "crypto", "bitcoin", "stock", "trading", "stripe", "paypal", "金融", "支付", "银行", "发票", "股票", "交易", "加密货币"] },
71
+ { id: "geo", label: "地理与地图", icon: "🗺️",
72
+ keywords: ["geography", "geospatial", "map", "gps", "location", "gis", "coordinates", "地理", "地图", "定位", "坐标", "空间数据"] },
73
+ { id: "education", label: "教育与学习", icon: "🎓",
74
+ keywords: ["education", "learning", "teaching", "course", "lesson", "quiz", "flashcard", "education", "教育", "学习", "课程", "教学", "辅导", "卡片"] },
75
+ { id: "ops", label: "运维与监控", icon: "📙",
76
+ keywords: ["monitoring", "observability", "metrics", "logging", "alert", "prometheus", "grafana", "uptime", "运维", "监控", "日志", "告警", "指标", "可观测性"] },
77
+ { id: "security", label: "安全与身份", icon: "🔐",
78
+ keywords: ["security", "authentication", "authorization", "vault", "password", "token", "identity", "oauth", "安全", "身份", "认证", "授权", "密码", "密钥", "access control"] },
79
+ { id: "other", label: "其他", icon: "📦",
80
+ keywords: [] }
81
+ ];
82
+
83
+ // ─────────────────────────── Windows 运行时探测 ───────────────────────────
84
+ // dsh-mcp-client 的 stdio 用 spawn 不经 shell → npx(.cmd) 在 Windows 会失败,
85
+ // 必须用 node.exe + npx-cli.js。此处运行时探测候选路径,探测不到退回裸命令并在 warn 里说明。
86
+
87
+ var _npxCache = null;
88
+ var _uvxCache = null;
89
+
90
+ export function probeNodeNpx() {
91
+ if (_npxCache) return _npxCache;
92
+ var node = "";
93
+ var npx = "";
94
+ var nodeCandidates = [DEFAULT_NODE_EXE, process.execPath];
95
+ for (var i = 0; i < nodeCandidates.length; i++) {
96
+ var nc = nodeCandidates[i];
97
+ if (nc && existsSync(nc)) { node = nc; break; }
98
+ }
99
+ if (!node && process.execPath) node = process.execPath;
100
+ var dir = node ? dirname(node) : "";
101
+ var npxCandidates = [];
102
+ if (dir) npxCandidates.push(join(dir, "node_modules", "npm", "bin", "npx-cli.js"));
103
+ // 兼容 nodejs 目录安装(npx-cli 往往就在 npm 包同目录下的 bin)
104
+ npxCandidates.push(DEFAULT_NPX_CLI);
105
+ for (var j = 0; j < npxCandidates.length; j++) {
106
+ var ncj = npxCandidates[j];
107
+ try { if (ncj && existsSync(ncj)) { npx = ncj; break; } } catch (e) { }
108
+ }
109
+ var warn = "";
110
+ if (!node) { node = "node"; warn = "未探测到 node.exe,将用裸 node 命令"; }
111
+ if (!npx) {
112
+ npx = "";
113
+ warn = (warn ? warn + ";" : "") + "未探测到 npx-cli.js,npm 包安装可能失败(Windows 下不能直接用 npx)";
114
+ }
115
+ _npxCache = { command: node, npx: npx, warn: warn };
116
+ return _npxCache;
117
+ }
118
+
119
+ export function probeUvx() {
120
+ if (_uvxCache) return _uvxCache;
121
+ var candidates = [DEFAULT_UVX];
122
+ try {
123
+ var lap = process.env.LOCALAPPDATA;
124
+ if (lap) candidates.push(join(lap, "Programs", "uv", "uvx.exe"));
125
+ } catch (e) { }
126
+ var cmd = "";
127
+ var warn = "";
128
+ for (var i = 0; i < candidates.length; i++) {
129
+ try { if (candidates[i] && existsSync(candidates[i])) { cmd = candidates[i]; break; } } catch (e) { }
130
+ }
131
+ if (!cmd) { cmd = "uvx"; warn = "未探测到 uvx.exe,pypi 包安装可能失败"; }
132
+ _uvxCache = { command: cmd, warn: warn };
133
+ return _uvxCache;
134
+ }
135
+
136
+ // ─────────────────────────── 工具函数 ───────────────────────────
137
+
138
+ function slugify(name) {
139
+ var s = String(name || "").toLowerCase();
140
+ s = s.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
141
+ return s || "x";
142
+ }
143
+
144
+ function normalizeServerName(name) {
145
+ var s = String(name || "");
146
+ return /^[a-zA-Z0-9_-]{1,32}$/.test(s) ? s : null;
147
+ }
148
+
149
+ function truncate(s, n) {
150
+ var t = String(s || "");
151
+ if (t.length <= n) return t;
152
+ return t.slice(0, n - 1) + "…";
153
+ }
154
+
155
+ // YAML 安全引号:值含 : # { } 或首尾空格或为空时用单引号包裹,并把内部单引号转义为 ''
156
+ function yamlStr(v) {
157
+ var s = String(v == null ? "" : v);
158
+ if (s === "") return "''";
159
+ var needs = /[:#{}\[\],&*!|>'"%@`]/.test(s) || /^\s|\s$/.test(s) || s !== String(s).trim();
160
+ if (/^[0-9]+$/.test(s) || /^(true|false|null|yes|no|on|off)$/i.test(s)) needs = true; // 数字/布尔仍需引号防止被当标量
161
+ if (needs) {
162
+ return "'" + s.replace(/'/g, "''") + "'";
163
+ }
164
+ return s;
165
+ }
166
+
167
+ // ─────────────────────────── 分类 ───────────────────────────
168
+
169
+ export function classify(text) {
170
+ var joined = String(text || "").toLowerCase();
171
+ var bestIdx = MARKET_CATS.length - 1; // 默认 other
172
+ var bestScore = 0;
173
+ for (var i = 0; i < MARKET_CATS.length - 1; i++) {
174
+ var cat = MARKET_CATS[i];
175
+ var score = 0;
176
+ for (var k = 0; k < cat.keywords.length; k++) {
177
+ var kw = cat.keywords[k];
178
+ if (!kw) continue;
179
+ if (joined.indexOf(kw) >= 0) score += kw.length;
180
+ }
181
+ if (score > bestScore) { bestScore = score; bestIdx = i; }
182
+ }
183
+ var c = MARKET_CATS[bestIdx];
184
+ return { category: c.id, categoryLabel: c.label, categoryIcon: c.icon };
185
+ }
186
+
187
+ // ─────────────────────────── 拉取官方 Registry(分页直到 nextCursor 为 null 或 30 页) ───────────────────────────
188
+
189
+ function httpFetchJson(url) {
190
+ return new Promise(function (resolve, reject) {
191
+ var ac = new AbortController();
192
+ var timer = setTimeout(function () { ac.abort(); }, FETCH_TIMEOUT_MS);
193
+ function cleanup() { if (timer) { clearTimeout(timer); timer = null; } }
194
+ fetch(url, { signal: ac.signal })
195
+ .then(function (res) {
196
+ cleanup();
197
+ if (!res.ok) { reject(new Error("HTTP " + res.status)); return null; }
198
+ return res.json();
199
+ })
200
+ .then(function (js) {
201
+ if (js != null) resolve(js);
202
+ }, function (e) {
203
+ cleanup();
204
+ reject(e);
205
+ });
206
+ });
207
+ }
208
+
209
+ // 返回原始 servers[] 数组(每项是外层 {server:{...}} 对象),原样返回
210
+ export async function fetchRegistry(opts) {
211
+ opts = opts || {};
212
+ var maxPages = opts.maxPages || MAX_PAGES;
213
+ var cursor = null;
214
+ var out = [];
215
+ var base = opts.base || REGISTRY_BASE;
216
+ for (var p = 0; p < maxPages; p++) {
217
+ var url = base + "?limit=" + PAGE_LIMIT + (cursor ? "&cursor=" + encodeURIComponent(cursor) : "");
218
+ var js = await httpFetchJson(url);
219
+ var list = (js && js.servers) || [];
220
+ for (var i = 0; i < list.length; i++) out.push(list[i]);
221
+ var meta = (js && js.metadata) || {};
222
+ var next = meta.nextCursor;
223
+ if (!next || next === cursor) break;
224
+ cursor = next;
225
+ }
226
+ return out;
227
+ }
228
+
229
+ // ─────────────────────────── registry → 市场条目 ───────────────────────────
230
+
231
+ function registryToEntry(raw) {
232
+ var s = (raw && raw.server) ? raw.server : raw;
233
+ if (!s) return null;
234
+ // serverName 取值优先级:① 首个包里合法的 npm/pypi 包名 identifier(如 @modelcontextprotocol/server-memory)
235
+ // ② 原始 server.name 若合规;③ 否则转成安全的 kebab slug。
236
+ // 注:registry 顶层 server.name 往往是 `ac.inference.sh/mcp` 这类服务 slug,
237
+ // 绝大多数不含 ^[a-zA-Z0-9_-]{1,32}$,故不可直接当 serverName,需回退到包名/slug。
238
+ var pkgs = (s.packages || []).filter(function (p) { return p; });
239
+ var remotes = (s.remotes || []).filter(function (r) { return r; });
240
+ var ident = pkgs.length && pkgs[0].identifier ? String(pkgs[0].identifier) : "";
241
+ var name = null;
242
+ if (ident && /^[a-zA-Z0-9_-]{1,32}$/.test(ident)) name = ident;
243
+ else if (normalizeServerName(s.name)) name = s.name;
244
+ else if (ident && /^@?[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(ident)) {
245
+ // npm 包名含 @ 作用域/斜杠时转 slug(@scope/pkg -> scope-pkg)
246
+ var slug = ident.replace(/^@/, "").replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
247
+ if (slug && slug.length <= 32 && /^[a-zA-Z0-9_-]{1,32}$/.test(slug)) name = slug;
248
+ }
249
+ if (!name) {
250
+ // 兜底:把 server.name 洗净成 slug
251
+ var rawSlug = slugify(String(s.name || s.title || ident || ""));
252
+ if (rawSlug.length > 32) rawSlug = rawSlug.slice(0, 32).replace(/-+$/, "");
253
+ if (rawSlug && /^[a-zA-Z0-9_-]{1,32}$/.test(rawSlug)) name = rawSlug;
254
+ else return null;
255
+ }
256
+ var title = String(s.title || s.name || name);
257
+ var description = truncate(s.description || s.title || "", 300);
258
+ var cls = classify(title + " " + s.description + " " + name);
259
+ var homepage = "";
260
+ var repository = "";
261
+ try { if (s.websiteUrl) homepage = String(s.websiteUrl); } catch (e) { }
262
+ try { if (s.repository && s.repository.url) repository = String(s.repository.url); } catch (e) { }
263
+ if (!homepage && repository) homepage = repository;
264
+ var icon = "";
265
+ try { if (s.icons && s.icons.length && s.icons[0] && s.icons[0].src) icon = String(s.icons[0].src); } catch (e) { }
266
+ var version = String(s.version || "");
267
+
268
+ var install = { kind: "remote", pkg: "", command: "", args: [], url: "", runtimeHint: "", env: {}, warn: "" };
269
+ var free = false, installable = false, needsKey = false, envRequired = [];
270
+
271
+ if (pkgs.length) {
272
+ var p0 = pkgs[0];
273
+ var rt = p0.registryType || "";
274
+ ident = String(p0.identifier || "");
275
+ install.runtimeHint = p0.runtimeHint || "";
276
+ if (rt === "npm") {
277
+ install.kind = "npm";
278
+ install.pkg = ident;
279
+ var np = probeNodeNpx();
280
+ install.command = np.command;
281
+ install.args = [];
282
+ if (np.npx) install.args.push(np.npx);
283
+ install.args.push("-y");
284
+ if (ident) install.args.push(ident);
285
+ if (np.warn) install.warn = np.warn;
286
+ free = true; installable = true;
287
+ } else if (rt === "pypi") {
288
+ install.kind = "pypi";
289
+ install.pkg = ident;
290
+ var uv = probeUvx();
291
+ install.command = uv.command;
292
+ install.args = [];
293
+ if (ident) install.args.push(ident);
294
+ if (uv.warn) install.warn = uv.warn;
295
+ free = true; installable = true;
296
+ } else { // oci / mcpb:本机无法直接安装
297
+ install.kind = rt;
298
+ install.pkg = ident;
299
+ free = false; installable = false;
300
+ }
301
+ // 收集所有包必填环境变量
302
+ var seen = {};
303
+ for (var i = 0; i < pkgs.length; i++) {
304
+ var p = pkgs[i];
305
+ if (!p.environmentVariables) continue;
306
+ for (var j = 0; j < p.environmentVariables.length; j++) {
307
+ var ev = p.environmentVariables[j];
308
+ if (!ev || !ev.name || seen[ev.name]) continue;
309
+ seen[ev.name] = true;
310
+ if (ev.isRequired) {
311
+ needsKey = true;
312
+ envRequired.push(ev.name);
313
+ }
314
+ }
315
+ }
316
+ } else if (remotes.length) {
317
+ install.kind = "remote";
318
+ install.url = String(remotes[0].url || "");
319
+ free = false; installable = false; needsKey = true;
320
+ }
321
+ // 既无 packages 也无 remotes → 保持 free/installable=false
322
+
323
+ return {
324
+ id: "mcp-market-" + slugify(name),
325
+ name: name,
326
+ title: title,
327
+ description: description,
328
+ category: cls.category,
329
+ categoryLabel: cls.categoryLabel,
330
+ categoryIcon: cls.categoryIcon,
331
+ subCategory: "registry",
332
+ subCategoryLabel: "官方注册表",
333
+ homepage: homepage,
334
+ repository: repository,
335
+ icon: icon,
336
+ version: version,
337
+ free: free,
338
+ installable: installable,
339
+ needsKey: needsKey,
340
+ envRequired: envRequired,
341
+ install: install,
342
+ source: "registry"
343
+ };
344
+ }
345
+
346
+ // ─────────────────────────── 精选目录 → 市场条目 ───────────────────────────
347
+
348
+ function curatedToEntry(item) {
349
+ var name = normalizeServerName(item.name);
350
+ if (!name) return null;
351
+ var pkg = String(item.package || "");
352
+ var install = { kind: "remote", pkg: pkg, command: "", args: [], url: "", runtimeHint: "", env: {}, warn: "" };
353
+ if (item.registryType === "npm" && pkg) {
354
+ install.kind = "npm";
355
+ var np = probeNodeNpx();
356
+ install.command = np.command;
357
+ install.args = [];
358
+ if (np.npx) install.args.push(np.npx);
359
+ install.args.push("-y");
360
+ install.args.push(pkg);
361
+ if (np.warn) install.warn = np.warn;
362
+ } else if (item.registryType === "pypi" && pkg) {
363
+ install.kind = "pypi";
364
+ var uv = probeUvx();
365
+ install.command = uv.command;
366
+ install.args = [pkg];
367
+ if (uv.warn) install.warn = uv.warn;
368
+ } else {
369
+ install.url = item.homepage || item.repository || "";
370
+ }
371
+ return {
372
+ id: "mcp-market-" + slugify(name),
373
+ name: name,
374
+ title: String(item.title || name),
375
+ description: truncate(item.descriptionZh || "", 300),
376
+ category: item.category,
377
+ categoryLabel: item.categoryLabel,
378
+ categoryIcon: item.categoryIcon,
379
+ subCategory: item.subCategory || "official",
380
+ subCategoryLabel: item.subCategoryLabel || "官方出品",
381
+ homepage: item.homepage || item.repository || "",
382
+ repository: item.repository || "",
383
+ // v2.0.7: 精选条目可以自带 icon(真实 logo URL);留空则由前端按其 GitHub 属主头像回退,
384
+ // 这样每条 MCP 显示的都是它自己的图标,而不是统一的分类 emoji。
385
+ icon: String(item.icon || ""),
386
+ version: "",
387
+ free: true,
388
+ installable: true,
389
+ needsKey: !!item.needsKey,
390
+ envRequired: (item.envRequired || []).slice(),
391
+ install: install,
392
+ source: "curated"
393
+ };
394
+ }
395
+
396
+ // ─────────────────────────── 缓存读写 ───────────────────────────
397
+
398
+ function marketFile() { return join(dataDir(), "market.json"); }
399
+
400
+ function readMarketCache() {
401
+ var f = marketFile();
402
+ try {
403
+ if (!existsSync(f)) return null;
404
+ var st = statSync(f);
405
+ if (Date.now() - st.mtime.getTime() > CACHE_TTL_MS) return { stale: true };
406
+ var js = JSON.parse(readFileSync(f, "utf8"));
407
+ if (js && js.ok && js.servers) return { data: js };
408
+ return null;
409
+ } catch (e) { return null; }
410
+ }
411
+
412
+ function writeMarketCache(result) {
413
+ var f = marketFile();
414
+ try {
415
+ mkdirSync(dirname(f), { recursive: true });
416
+ writeFileSync(f, JSON.stringify(result), "utf8");
417
+ return true;
418
+ } catch (e) { return false; }
419
+ }
420
+
421
+ // ─────────────────────────── 组装市场 ───────────────────────────
422
+
423
+ function marketCuratedPath() {
424
+ // 用 fileURLToPath 而非 URL.pathname:Windows 下 pathname 会带前导 /C:/...,
425
+ // 被 join 拼成 \C:\... 导致 existsSync false,精选目录永远读不到。
426
+ return join(dirname(fileURLToPath(import.meta.url)), "market-curated.json");
427
+ }
428
+
429
+ function loadCurated() {
430
+ try {
431
+ var curPath = marketCuratedPath();
432
+ var raw = readFileSync(curPath, "utf8");
433
+ var js = JSON.parse(raw);
434
+ return (js && js.items) || [];
435
+ } catch (e) { return []; }
436
+ }
437
+
438
+ function buildCategories(servers) {
439
+ var count = {};
440
+ for (var i = 0; i < servers.length; i++) {
441
+ var c = servers[i].category;
442
+ if (c && count[c] != null) count[c] = count[c] + 1; else if (c) count[c] = 1;
443
+ }
444
+ var out = [];
445
+ for (var k = 0; k < MARKET_CATS.length; k++) {
446
+ var cat = MARKET_CATS[k];
447
+ var n = count[cat.id] || 0;
448
+ if (n > 0) out.push({ id: cat.id, label: cat.label, icon: cat.icon, count: n });
449
+ }
450
+ return out;
451
+ }
452
+
453
+ export async function buildMarket(ctx, opts) {
454
+ opts = opts || {};
455
+ var refresh = !!opts.refresh;
456
+ var curatedRaw = loadCurated();
457
+
458
+ // 精选始终组装(优先,永不缓存覆盖)
459
+ var curatedSrv = [];
460
+ var curatedByName = {};
461
+ for (var c = 0; c < curatedRaw.length; c++) {
462
+ var ce = curatedToEntry(curatedRaw[c]);
463
+ if (!ce) continue;
464
+ curatedSrv.push(ce);
465
+ curatedByName[ce.name.toLowerCase()] = true;
466
+ }
467
+
468
+ // 缓存复用(非 refresh 且 24h 内)
469
+ if (!refresh) {
470
+ var hit = readMarketCache();
471
+ if (hit && hit.data) {
472
+ // 合并精选(缓存的精选条目丢弃,用全新精选)
473
+ var cachedBy = {};
474
+ for (var i = 0; i < (hit.data.servers || []).length; i++) {
475
+ var srv = hit.data.servers[i];
476
+ if (!srv || srv.source === "curated") continue;
477
+ cachedBy[srv.name.toLowerCase()] = srv;
478
+ }
479
+ var merged = curatedSrv.slice();
480
+ var have = {};
481
+ for (var m = 0; m < merged.length; m++) have[merged[m].name.toLowerCase()] = true;
482
+ for (var nm in cachedBy) {
483
+ if (!have[nm]) { merged.push(cachedBy[nm]); have[nm] = true; }
484
+ }
485
+ return {
486
+ ok: true,
487
+ ts: hit.data.ts || Date.now(),
488
+ cached: true,
489
+ stale: false,
490
+ warn: hit.data.warn || "",
491
+ total: merged.length,
492
+ hiddenByCurated: 0,
493
+ categories: buildCategories(merged),
494
+ servers: merged
495
+ };
496
+ }
497
+ }
498
+
499
+ // 拉 registry
500
+ var registryRaw = [];
501
+ var warn = "";
502
+ var fetchFailed = false;
503
+ try {
504
+ registryRaw = await fetchRegistry({});
505
+ } catch (e) {
506
+ fetchFailed = true;
507
+ warn = "官方 Registry 拉取失败:" + String((e && e.message) || e);
508
+ }
509
+
510
+ // 网络失败:有旧缓存 → 旧缓存 + stale;无缓存 → 只精选 + stale
511
+ if (fetchFailed) {
512
+ if (!refresh) {
513
+ var hit2 = readMarketCache();
514
+ if (hit2 && hit2.data) {
515
+ hit2.data.cached = true;
516
+ hit2.data.stale = true;
517
+ hit2.data.warn = warn;
518
+ return hit2.data;
519
+ }
520
+ }
521
+ var ct = buildCategories(curatedSrv);
522
+ return {
523
+ ok: true, ts: Date.now(), cached: false, stale: true, warn: warn,
524
+ total: curatedSrv.length, hiddenByCurated: 0, categories: ct, servers: curatedSrv
525
+ };
526
+ }
527
+
528
+ // 正常组装:精选优先,registry 按 name(小写)去重(保留首个出现的条目,
529
+ // registry 顺序即最新/首个),与 cached 路径 recoveredBy[name] 口径一致。
530
+ // total = 去重后 merged 总数(精选 29 条 + 去重后 registry)。
531
+ var merged = curatedSrv.slice();
532
+ var haveName = {};
533
+ for (var i0 = 0; i0 < merged.length; i0++) haveName[merged[i0].name.toLowerCase()] = true;
534
+ var hiddenByCurated = 0; // 被精选覆盖(同名存在于 curated)的 registry 条目数
535
+ var registrySeen = {}; // registry 内部同名去重(同一 server 各版本)
536
+ for (var r = 0; r < registryRaw.length; r++) {
537
+ var e2 = registryToEntry(registryRaw[r]);
538
+ if (!e2) continue;
539
+ var key = e2.name.toLowerCase();
540
+ if (registrySeen[key]) continue; // registry 内部版本重复:丢弃
541
+ registrySeen[key] = true;
542
+ if (haveName[key]) { hiddenByCurated++; continue; } // 被精选同名校覆盖
543
+ merged.push(e2);
544
+ haveName[key] = true;
545
+ }
546
+
547
+ var result = {
548
+ ok: true,
549
+ ts: Date.now(),
550
+ cached: false,
551
+ stale: false,
552
+ warn: warn,
553
+ total: merged.length,
554
+ hiddenByCurated: hiddenByCurated,
555
+ categories: buildCategories(merged),
556
+ servers: merged
557
+ };
558
+
559
+ writeMarketCache(result);
560
+ return result;
561
+ }
562
+
563
+ // ─────────────────────────── 兼容导出(供 installMcp / 前端诊断使用) ───────────────────────────
564
+
565
+ export var MARKET_META = {
566
+ base: REGISTRY_BASE,
567
+ limit: PAGE_LIMIT,
568
+ maxPages: MAX_PAGES,
569
+ cacheFile: marketFile
570
+ };