dsh-mobile-plugin 0.5.40 → 0.5.43
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/config/agent-presets/standard/agent.cordis.yml +14 -0
- package/docs/extension-authoring.md +183 -42
- package/docs/extension-sample/README.md +2 -3
- package/dsh-mobile-credentials/lib/credentials.js +193 -66
- package/lib/client.js +1 -94
- package/lib/desktop-half-stats.cjs +2 -12
- package/lib/host-compat.cjs +2 -0
- package/lib/http/routing.js +2 -2
- package/lib/mobile/answer-sources.js +5 -4
- package/lib/mobile/events.js +2 -24
- package/lib/mobile/extension-catalog.js +95 -14
- package/lib/mobile/file-read.js +12 -36
- package/lib/mobile/file-stat.js +31 -0
- package/lib/mobile/history-derive.js +142 -5
- package/lib/mobile/host-bridge/endpoints.js +8 -0
- package/lib/mobile/host-bridge/shims.js +10 -2
- package/lib/mobile/permissions.js +8 -1
- package/lib/mobile/plugin-catalog.js +501 -0
- package/lib/mobile/presented-file-stats.js +244 -0
- package/lib/mobile/run-timeline.js +5 -2
- package/lib/mobile/session-artifacts.js +494 -0
- package/lib/mobile/session-cache.js +49 -1
- package/lib/mobile/session-file.js +232 -100
- package/lib/mobile/session-snapshot.js +19 -4
- package/lib/mobile/session-team.js +40 -0
- package/lib/mobile/stats-collect.cjs +21 -9
- package/lib/mobile/stats.js +45 -10
- package/lib/mobile/stream.js +24 -3
- package/lib/mobile/todo-phases.js +113 -0
- package/lib/mobile/wire-cut.js +27 -1
- package/lib/panel/index.html +8 -8
- package/lib/routes/control-plane.js +21 -23
- package/lib/routes/mobile-api.js +23 -11
- package/lib/shared/e2ee-chunks.js +23 -3
- package/package.json +1 -1
- package/lib/desktop-view.cjs +0 -124
- package/lib/mobile/promo-receiver.cjs +0 -77
- package/lib/shared/desktop-view-signal.js +0 -66
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 手机侧「DSH 插件市场」的清单服务:读社区精选清单,收窄成 App 要的那一页。
|
|
5
|
+
*
|
|
6
|
+
* 为什么是读社区清单,而不是我们自己的分发系统:这一页装的是**电脑上 DSH 的插件**
|
|
7
|
+
* (npm 包 / GitHub 仓库),社区那份清单(awesome-dsh-plugin.com,另有 jsDelivr 上的镜像
|
|
8
|
+
* 一份)已经把「有哪些、是谁的、多少 star / 下载、图标、截图、能力声明」维护好了——那是
|
|
9
|
+
* 别人的一份公开索引,我们照读即可,没有自己的审核流水线要养。
|
|
10
|
+
*
|
|
11
|
+
* 为什么不在手机上装包、也不自己跑 pnpm:装插件是宿主的活。DSH 里本来就有插件管理器
|
|
12
|
+
* (桌面端 设置 → 插件 那个页面背后的同一个服务),版本兼容检查、依赖脚本授权、失败回滚、
|
|
13
|
+
* 要不要重启才生效,全由它判断。插件侧只把清单削干净、把 `installSpec` 算好,安装动作交给
|
|
14
|
+
* 已有的 `POST /plugin/market/install`。能力面对手机只多「读一份公开 JSON」(外网 GET),
|
|
15
|
+
* 仍然不碰 shell、不碰系统设置、不写任意文件。
|
|
16
|
+
*
|
|
17
|
+
* 三个取舍:
|
|
18
|
+
* 1. **缓存收窄后的结果,不缓存原文**:源清单 14MB / 4MB,缓存原文等于在宿主进程里常驻
|
|
19
|
+
* 十几 MB;收窄后通常是几百 KB 到一两 MB。10 分钟有效,过期重拉。
|
|
20
|
+
* 2. **过期重拉失败不回旧缓存**:清单过期是错误答案,不是降级答案(与 dshmarket 自己的
|
|
21
|
+
* 判据一致)。宁可让手机说「读不到清单」,也不要让它按一周前的数据装一个已经下架的包。
|
|
22
|
+
* 3. **并发只允许一个在飞**:手机切搜索词、翻页会连续打这条接口,每次各拉 14MB 毫无意义。
|
|
23
|
+
* 其余请求等同一个 Promise。
|
|
24
|
+
*
|
|
25
|
+
* 接口:`GET /api/mobile/v1/plugin/catalog`(走 token 守卫),query 见 A3-101。
|
|
26
|
+
* 失败回 `{ ok:false, error:{ code:'catalog-unavailable', message } }`,message 里带上每个源
|
|
27
|
+
* 各自的失败原因(排查时最想知道的是「哪一个源、哪一步坏了」)。
|
|
28
|
+
*
|
|
29
|
+
* 清单里认不出的条目**整条丢弃**:`name` / `owner` / `repo` 缺一、repo 不是
|
|
30
|
+
* `https://github.com/<owner>/<repo>`、或与 owner 不一致,都不是能安装的东西,App 侧不再兜。
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const { sendJson } = require('../shared/http-util');
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 数据源,按顺序试,前一个失败才试下一个。两份清单是社区同一批数据的两条腿:
|
|
37
|
+
* 主源字段全(star / 下载 / 图标 / 截图 / 收录时间),镜像源只剩名字、说明、仓库与版本。
|
|
38
|
+
*/
|
|
39
|
+
const SOURCES = [
|
|
40
|
+
{
|
|
41
|
+
id: 'awesome',
|
|
42
|
+
url: 'https://awesome-dsh-plugin.com/plugins.json',
|
|
43
|
+
// { categories: { id: {en,zh} }, plugins: [...] }
|
|
44
|
+
format: 'plugins',
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
id: 'index',
|
|
48
|
+
url: 'https://cdn.jsdelivr.net/npm/dsh-plugin-catalog/index.json',
|
|
49
|
+
// { format: 1, metadata: { categories: { id: { title } } }, plugins: [...] }
|
|
50
|
+
format: 'index',
|
|
51
|
+
},
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
/** 缓存有效期:清单一天更新不了几次,10 分钟足够新,也不至于每次翻页都拉 14MB。 */
|
|
55
|
+
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
56
|
+
/** 每个源最多试两次:14MB 的 CDN 偶发断流很常见,一次失败不代表源坏了。 */
|
|
57
|
+
const ATTEMPTS_PER_SOURCE = 2;
|
|
58
|
+
/** 单次拉取的等待上限。14MB 在慢网络上也要留够时间,但绝不能无限等。 */
|
|
59
|
+
const FETCH_TIMEOUT_MS = 30 * 1000;
|
|
60
|
+
|
|
61
|
+
/** 文案每门语言的字数上限(契约:600)。 */
|
|
62
|
+
const TEXT_MAX_CHARS = 600;
|
|
63
|
+
/** 图标只认 https 绝对地址;截图最多 4 张;能力最多 12 项(契约)。 */
|
|
64
|
+
const SCREENSHOTS_MAX = 4;
|
|
65
|
+
const CAPABILITIES_MAX = 12;
|
|
66
|
+
/** 搜索词上限 100 字,超了截断而不是报错:手机输入框不会让用户数到 100。 */
|
|
67
|
+
const Q_MAX_CHARS = 100;
|
|
68
|
+
/** 分页:缺省 20 条,最多 60 条一页(手机一屏装不下更多,再大只是白算)。 */
|
|
69
|
+
const LIMIT_DEFAULT = 20;
|
|
70
|
+
const LIMIT_MAX = 60;
|
|
71
|
+
|
|
72
|
+
const SORTS = ['downloads', 'stars', 'added', 'name'];
|
|
73
|
+
const DIRS = ['asc', 'desc'];
|
|
74
|
+
/** 条目没有分类时的落点:它仍会出现在「全部」里,只是不属于任何一颗胶囊。 */
|
|
75
|
+
const FALLBACK_CATEGORY = 'other';
|
|
76
|
+
|
|
77
|
+
/** 一份 `https://github.com/<owner>/<repo>`;允许尾部 `.git` 与多余斜杠,输出统一成干净形状。 */
|
|
78
|
+
const GITHUB_REPO = /^https:\/\/github\.com\/([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/;
|
|
79
|
+
/** npm 包名(含 scope)。只有合法名字才当安装目标,否则退回 github: 形态。 */
|
|
80
|
+
const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
|
|
81
|
+
const NPM_NAME_MAX = 214;
|
|
82
|
+
/** 收录日期只认 `YYYY-MM-DD`。 */
|
|
83
|
+
const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
84
|
+
|
|
85
|
+
/** 收窄后的缓存:{ source, fetchedAt, fetchedAtWall, items, categories }。 */
|
|
86
|
+
let cache = null;
|
|
87
|
+
/** 正在飞的那一次拉取;并发请求等它。 */
|
|
88
|
+
let inflight = null;
|
|
89
|
+
/** 测试注入点:假 fetch 与假时钟。真跑时就是全局 fetch / Date.now。 */
|
|
90
|
+
let fetchImpl = null;
|
|
91
|
+
let clock = null;
|
|
92
|
+
|
|
93
|
+
function nowMs() {
|
|
94
|
+
return clock ? clock() : Date.now();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function errorText(error) {
|
|
98
|
+
if (!error) return '未知错误';
|
|
99
|
+
if (typeof error.message === 'string' && error.message) return error.message;
|
|
100
|
+
return String(error);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 非空字符串才收,其余 null;`max` 用来挡掉离谱长的字段。 */
|
|
104
|
+
function textOrNull(value, max = 300) {
|
|
105
|
+
if (typeof value !== 'string') return null;
|
|
106
|
+
const text = value.trim();
|
|
107
|
+
return text ? (max ? text.slice(0, max) : text) : null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 只认 https 绝对地址:http 会混合内容、其它协议 App 也画不出来。 */
|
|
111
|
+
function httpsOrNull(value, max = 1000) {
|
|
112
|
+
const text = textOrNull(value, max);
|
|
113
|
+
if (!text) return null;
|
|
114
|
+
try {
|
|
115
|
+
return new URL(text).protocol === 'https:' ? text : null;
|
|
116
|
+
} catch {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 双语表:只留「语言 → 非空字符串」的项,每门语言截到 600 字;一项都不剩时是 `null`
|
|
123
|
+
* (不是空对象 —— App 侧据此判断「这条没有文案」)。
|
|
124
|
+
*/
|
|
125
|
+
function localizedOf(value) {
|
|
126
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
127
|
+
const out = {};
|
|
128
|
+
for (const [language, text] of Object.entries(value)) {
|
|
129
|
+
const clean = textOrNull(text, TEXT_MAX_CHARS);
|
|
130
|
+
if (clean) out[language] = clean;
|
|
131
|
+
}
|
|
132
|
+
return Object.keys(out).length ? out : null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 非负安全整数,否则 null(`stars` 那里再由调用方退成 0)。 */
|
|
136
|
+
function countOf(value) {
|
|
137
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return null;
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 分类字段可能是字符串或字符串数组,取第一个可用值。 */
|
|
142
|
+
function firstString(value) {
|
|
143
|
+
if (typeof value === 'string') return textOrNull(value, 64);
|
|
144
|
+
if (Array.isArray(value)) {
|
|
145
|
+
for (const entry of value) {
|
|
146
|
+
const clean = textOrNull(entry, 64);
|
|
147
|
+
if (clean) return clean;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** `https://` 截图数组,最多 4 张。 */
|
|
154
|
+
function screenshotsOf(value) {
|
|
155
|
+
if (!Array.isArray(value)) return [];
|
|
156
|
+
const out = [];
|
|
157
|
+
for (const entry of value) {
|
|
158
|
+
const url = httpsOrNull(entry);
|
|
159
|
+
if (url && out.length < SCREENSHOTS_MAX) out.push(url);
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 能力声明:只留字符串,最多 12 项,重复的不给第二份。 */
|
|
165
|
+
function capabilitiesOf(value) {
|
|
166
|
+
if (!Array.isArray(value)) return [];
|
|
167
|
+
const out = [];
|
|
168
|
+
for (const entry of value) {
|
|
169
|
+
const name = textOrNull(entry, 64);
|
|
170
|
+
if (name && !out.includes(name) && out.length < CAPABILITIES_MAX) out.push(name);
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 仓库地址解析:只认 `https://github.com/<owner>/<repo>`,统一成不带 `.git` / 尾斜杠的形状。
|
|
177
|
+
* 返回 null 表示这条不该进清单。
|
|
178
|
+
*/
|
|
179
|
+
function parseRepo(value) {
|
|
180
|
+
const text = textOrNull(value, 300);
|
|
181
|
+
if (!text) return null;
|
|
182
|
+
const match = GITHUB_REPO.exec(text);
|
|
183
|
+
if (!match) return null;
|
|
184
|
+
return { owner: match[1], repo: match[2], url: `https://github.com/${match[1]}/${match[2]}` };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* 一条原始记录 → 契约里的 Item;认不出就 null。
|
|
189
|
+
*
|
|
190
|
+
* `raw.owner` 有值时必须与 repo 里的 owner 一致(大小写不敏感):清单里这两格打架的条目,
|
|
191
|
+
* 装起来只会给人装错仓库。镜像源没有 owner 字段,从仓库地址里解析。
|
|
192
|
+
*/
|
|
193
|
+
function normalizeItem(raw, sourceId) {
|
|
194
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
195
|
+
const name = textOrNull(raw.name, 200);
|
|
196
|
+
if (!name) return null;
|
|
197
|
+
const repoUrl = sourceId === 'index'
|
|
198
|
+
? (raw.repository && raw.repository.url)
|
|
199
|
+
: (raw.url || (raw.repository && raw.repository.url));
|
|
200
|
+
const parsed = parseRepo(repoUrl);
|
|
201
|
+
if (!parsed) return null;
|
|
202
|
+
const declaredOwner = textOrNull(raw.owner, 100);
|
|
203
|
+
if (declaredOwner && declaredOwner.toLowerCase() !== parsed.owner.toLowerCase()) return null;
|
|
204
|
+
|
|
205
|
+
// 镜像源没有 npm 字段:它的 `name` 就是 npm 包名(契约这么写的)。
|
|
206
|
+
const npm = textOrNull(sourceId === 'index' ? raw.name : raw.npm, NPM_NAME_MAX);
|
|
207
|
+
// 分类:主源在顶层 `category`,镜像源在 `metadata.category`(都可能是字符串或数组)。
|
|
208
|
+
const rawCategory = sourceId === 'index' && raw.metadata ? raw.metadata.category : raw.category;
|
|
209
|
+
const npmValid = npm && NPM_NAME.test(npm) ? npm : null;
|
|
210
|
+
|
|
211
|
+
// 版本:主源给 `version`,镜像源给 `versions: [{ version }]` 取第一条。
|
|
212
|
+
const version = textOrNull(
|
|
213
|
+
raw.version || (Array.isArray(raw.versions) && raw.versions[0] && raw.versions[0].version),
|
|
214
|
+
64,
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
const stars = countOf(raw.stars);
|
|
218
|
+
const downloads = countOf(raw.downloads);
|
|
219
|
+
const added = textOrNull(raw.added, 32);
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
name,
|
|
223
|
+
owner: parsed.owner,
|
|
224
|
+
repo: parsed.url,
|
|
225
|
+
category: firstString(rawCategory) || FALLBACK_CATEGORY,
|
|
226
|
+
title: localizedOf(raw.title),
|
|
227
|
+
description: localizedOf(raw.description),
|
|
228
|
+
npm: npmValid,
|
|
229
|
+
version,
|
|
230
|
+
stars: stars === null ? 0 : stars,
|
|
231
|
+
downloads,
|
|
232
|
+
icon: httpsOrNull(raw.icon),
|
|
233
|
+
screenshots: screenshotsOf(raw.screenshots),
|
|
234
|
+
capabilities: capabilitiesOf(raw.capabilities),
|
|
235
|
+
// 安装目标是宿主算好的:有合法 npm 名就用它,否则让插件管理器按 GitHub 仓库去装。
|
|
236
|
+
installSpec: npmValid || `github:${parsed.owner}/${parsed.repo}`,
|
|
237
|
+
added: added && DAY_PATTERN.test(added) ? added : null,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 两份清单的形状差异只在这里抹平:返回 { categories, items }。
|
|
243
|
+
* `items` 已去重(按 `owner/name`,同一份清单里同名同源的两条只留第一条)。
|
|
244
|
+
*/
|
|
245
|
+
function narrowCatalog(document, source) {
|
|
246
|
+
if (!document || typeof document !== 'object') throw new Error('返回的不是清单 JSON');
|
|
247
|
+
if (source.format === 'index' && document.format !== 1) {
|
|
248
|
+
throw new Error(`清单格式不认识(format=${String(document.format)})`);
|
|
249
|
+
}
|
|
250
|
+
const plugins = document.plugins;
|
|
251
|
+
if (!Array.isArray(plugins) || plugins.length === 0) throw new Error('清单里没有 plugins 数组');
|
|
252
|
+
|
|
253
|
+
// 分类:主源是 `categories: { id: {en,zh} }`,镜像源是 `metadata.categories: { id: { title } }`。
|
|
254
|
+
const rawCategories = source.format === 'index'
|
|
255
|
+
? (document.metadata && document.metadata.categories)
|
|
256
|
+
: document.categories;
|
|
257
|
+
const categories = [];
|
|
258
|
+
if (rawCategories && typeof rawCategories === 'object' && !Array.isArray(rawCategories)) {
|
|
259
|
+
for (const [id, value] of Object.entries(rawCategories)) {
|
|
260
|
+
const cleanId = textOrNull(id, 64);
|
|
261
|
+
if (!cleanId) continue;
|
|
262
|
+
const title = source.format === 'index'
|
|
263
|
+
? (localizedOf(value && value.title) || localizedOf(value))
|
|
264
|
+
: localizedOf(value);
|
|
265
|
+
// 分类没写文案时退回 id 当名字:胶囊总得有个字,不能画成空白。
|
|
266
|
+
categories.push({ id: cleanId, title: title || { en: cleanId } });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const seen = new Set();
|
|
271
|
+
const items = [];
|
|
272
|
+
for (const raw of plugins) {
|
|
273
|
+
const item = normalizeItem(raw, source.id);
|
|
274
|
+
if (!item) continue;
|
|
275
|
+
const key = `${item.owner}/${item.name}`.toLowerCase();
|
|
276
|
+
if (seen.has(key)) continue;
|
|
277
|
+
seen.add(key);
|
|
278
|
+
items.push(item);
|
|
279
|
+
}
|
|
280
|
+
if (items.length === 0) throw new Error('清单里没有一条可用的插件(缺仓库地址或名字)');
|
|
281
|
+
return { categories, items };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 拉一个源:读 JSON、把表单收窄。抛出的错误由 `loadCatalog` 记进失败原因。 */
|
|
285
|
+
async function fetchCatalogDocument(source) {
|
|
286
|
+
const doFetch = fetchImpl || globalThis.fetch;
|
|
287
|
+
if (typeof doFetch !== 'function') throw new Error('这个运行时里没有 fetch,拉不了清单');
|
|
288
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
289
|
+
const timer = controller ? setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS) : null;
|
|
290
|
+
let response;
|
|
291
|
+
try {
|
|
292
|
+
response = await doFetch(source.url, {
|
|
293
|
+
headers: { accept: 'application/json' },
|
|
294
|
+
signal: controller ? controller.signal : undefined,
|
|
295
|
+
});
|
|
296
|
+
} catch (error) {
|
|
297
|
+
throw new Error(`连不上:${errorText(error)}`);
|
|
298
|
+
} finally {
|
|
299
|
+
if (timer) clearTimeout(timer);
|
|
300
|
+
}
|
|
301
|
+
if (!response || response.ok !== true) {
|
|
302
|
+
const status = response && Number.isFinite(response.status) ? response.status : 0;
|
|
303
|
+
throw new Error(`HTTP ${status || '未知'}`);
|
|
304
|
+
}
|
|
305
|
+
try {
|
|
306
|
+
return await response.json();
|
|
307
|
+
} catch {
|
|
308
|
+
throw new Error('返回的不是 JSON');
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 按顺序试源,每个源最多两次;全挂了抛错,message 是每个源各自的失败原因拼接。
|
|
314
|
+
* 成功时把**收窄后**的结果塞进缓存(不是原文)。
|
|
315
|
+
*/
|
|
316
|
+
async function fetchCatalog() {
|
|
317
|
+
const failures = [];
|
|
318
|
+
for (const source of SOURCES) {
|
|
319
|
+
for (let attempt = 1; attempt <= ATTEMPTS_PER_SOURCE; attempt += 1) {
|
|
320
|
+
try {
|
|
321
|
+
const document = await fetchCatalogDocument(source);
|
|
322
|
+
const { categories, items } = narrowCatalog(document, source);
|
|
323
|
+
const fetchedAt = nowMs();
|
|
324
|
+
cache = {
|
|
325
|
+
source: source.url,
|
|
326
|
+
fetchedAt,
|
|
327
|
+
// 墙钟另存一份:`fetchedAt` 走可注入的时钟(测试用),这一格永远是真实时间。
|
|
328
|
+
fetchedAtWall: Date.now(),
|
|
329
|
+
items,
|
|
330
|
+
categories,
|
|
331
|
+
};
|
|
332
|
+
return cache;
|
|
333
|
+
} catch (error) {
|
|
334
|
+
failures.push(`${source.url} 第 ${attempt} 次:${errorText(error)}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
throw new Error(failures.join(';'));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* 取一份可用的收窄结果。
|
|
343
|
+
*
|
|
344
|
+
* - 缓存有效期内直接返回;
|
|
345
|
+
* - 过期 / 没有缓存时拉一次,**失败就抛**(绝不拿旧缓存冒充成功);
|
|
346
|
+
* - 并发只允许一个在飞:后来者 await 同一个 Promise。
|
|
347
|
+
*/
|
|
348
|
+
async function loadCatalog() {
|
|
349
|
+
const at = nowMs();
|
|
350
|
+
if (cache && at - cache.fetchedAt >= 0 && at - cache.fetchedAt < CACHE_TTL_MS) return cache;
|
|
351
|
+
if (!inflight) {
|
|
352
|
+
inflight = fetchCatalog().finally(() => { inflight = null; });
|
|
353
|
+
}
|
|
354
|
+
return inflight;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** 搜索词:名字 / 作者 / 仓库名 / 双语标题与说明 / npm 名,大小写不敏感。 */
|
|
358
|
+
function matchesQuery(item, needle) {
|
|
359
|
+
if (!needle) return true;
|
|
360
|
+
const haystack = [
|
|
361
|
+
item.name,
|
|
362
|
+
item.owner,
|
|
363
|
+
item.repo,
|
|
364
|
+
item.npm || '',
|
|
365
|
+
...Object.values(item.title || {}),
|
|
366
|
+
...Object.values(item.description || {}),
|
|
367
|
+
...item.capabilities,
|
|
368
|
+
].join('\n').toLowerCase();
|
|
369
|
+
return haystack.includes(needle);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** 排序值:缺一格时 `null`(排在最后,与 App 侧「缺哪格就不画」一致)。 */
|
|
373
|
+
function sortValue(item, sort) {
|
|
374
|
+
if (sort === 'downloads') return item.downloads;
|
|
375
|
+
if (sort === 'stars') return item.stars;
|
|
376
|
+
if (sort === 'added') return item.added;
|
|
377
|
+
return item.name.toLowerCase();
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* 比较:null 恒排最后(不管升序降序,都不该让「没有数据」冒到顶上——镜像源本来就没有
|
|
382
|
+
* 下载量,排在前面等于整页被一堆空数字占住)。
|
|
383
|
+
*/
|
|
384
|
+
function compareItems(a, b, sort, dir) {
|
|
385
|
+
const left = sortValue(a, sort);
|
|
386
|
+
const right = sortValue(b, sort);
|
|
387
|
+
if (left === null && right === null) return compareNames(a, b);
|
|
388
|
+
if (left === null) return 1;
|
|
389
|
+
if (right === null) return -1;
|
|
390
|
+
if (left === right) return compareNames(a, b);
|
|
391
|
+
const order = left < right ? -1 : 1;
|
|
392
|
+
return dir === 'asc' ? order : -order;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** 同值的兜底顺序:名字、再作者。翻页因此是确定性的,不会两页看到同一条。 */
|
|
396
|
+
function compareNames(a, b) {
|
|
397
|
+
const an = a.name.toLowerCase();
|
|
398
|
+
const bn = b.name.toLowerCase();
|
|
399
|
+
if (an !== bn) return an < bn ? -1 : 1;
|
|
400
|
+
const ao = a.owner.toLowerCase();
|
|
401
|
+
const bo = b.owner.toLowerCase();
|
|
402
|
+
if (ao !== bo) return ao < bo ? -1 : 1;
|
|
403
|
+
return 0;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** 取整数 query 参数;不是整数就退回缺省。 */
|
|
407
|
+
function intParam(raw, fallback) {
|
|
408
|
+
if (typeof raw !== 'string' || !/^\d+$/.test(raw.trim())) return fallback;
|
|
409
|
+
return Number.parseInt(raw.trim(), 10);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* query 清洗。排序 / 方向 / 分页的缺省与上限全部照契约;认不出的值退回缺省而不是报错
|
|
414
|
+
* (手机拼错一个参数不该让整页变红,界面上的胶囊本来就只会给合法值)。
|
|
415
|
+
*/
|
|
416
|
+
function parseQuery(searchParams) {
|
|
417
|
+
const q = textOrNull(searchParams.get('q'), Q_MAX_CHARS) || '';
|
|
418
|
+
const rawCategory = textOrNull(searchParams.get('category'), 64);
|
|
419
|
+
const category = rawCategory && rawCategory !== 'all' ? rawCategory : 'all';
|
|
420
|
+
const rawSort = textOrNull(searchParams.get('sort'), 16);
|
|
421
|
+
const sort = SORTS.includes(rawSort) ? rawSort : 'downloads';
|
|
422
|
+
const rawDir = textOrNull(searchParams.get('dir'), 8);
|
|
423
|
+
const dir = DIRS.includes(rawDir) ? rawDir : (sort === 'name' ? 'asc' : 'desc');
|
|
424
|
+
const offset = intParam(searchParams.get('offset'), 0);
|
|
425
|
+
const limit = Math.min(Math.max(intParam(searchParams.get('limit'), LIMIT_DEFAULT), 1), LIMIT_MAX);
|
|
426
|
+
return { q: q.toLowerCase(), category, sort, dir, offset, limit };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* 把一份收窄结果切成契约要的那一页。
|
|
431
|
+
*
|
|
432
|
+
* `categories` 的 `count` 只受搜索词影响、**不受 `category` 影响**:否则选中一颗胶囊之后
|
|
433
|
+
* 其余胶囊的计数全变 0,界面只能把它们藏起来,用户就再也切不回去了。
|
|
434
|
+
*/
|
|
435
|
+
function pageOf(catalog, query) {
|
|
436
|
+
const searched = query.q ? catalog.items.filter((item) => matchesQuery(item, query.q)) : catalog.items;
|
|
437
|
+
|
|
438
|
+
const counts = new Map();
|
|
439
|
+
for (const item of searched) counts.set(item.category, (counts.get(item.category) || 0) + 1);
|
|
440
|
+
const categories = catalog.categories.map((category) => ({
|
|
441
|
+
id: category.id,
|
|
442
|
+
title: category.title,
|
|
443
|
+
count: counts.get(category.id) || 0,
|
|
444
|
+
}));
|
|
445
|
+
|
|
446
|
+
const filtered = query.category === 'all'
|
|
447
|
+
? searched
|
|
448
|
+
: searched.filter((item) => item.category === query.category);
|
|
449
|
+
|
|
450
|
+
const sorted = filtered.slice().sort((a, b) => compareItems(a, b, query.sort, query.dir));
|
|
451
|
+
|
|
452
|
+
const items = sorted.slice(query.offset, query.offset + query.limit);
|
|
453
|
+
return {
|
|
454
|
+
source: catalog.source,
|
|
455
|
+
fetchedAt: catalog.fetchedAt,
|
|
456
|
+
total: sorted.length,
|
|
457
|
+
categories,
|
|
458
|
+
items,
|
|
459
|
+
hasMore: query.offset + items.length < sorted.length,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** GET /api/mobile/v1/plugin/catalog */
|
|
464
|
+
async function handlePluginCatalog(ctx, req, res) {
|
|
465
|
+
let catalog;
|
|
466
|
+
try {
|
|
467
|
+
catalog = await loadCatalog();
|
|
468
|
+
} catch (error) {
|
|
469
|
+
return sendJson(res, 503, {
|
|
470
|
+
ok: false,
|
|
471
|
+
error: { code: 'catalog-unavailable', message: errorText(error) },
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
let query;
|
|
475
|
+
try {
|
|
476
|
+
query = parseQuery(new URL((req && req.url) || '/', 'http://x').searchParams);
|
|
477
|
+
} catch {
|
|
478
|
+
query = parseQuery(new URLSearchParams());
|
|
479
|
+
}
|
|
480
|
+
const page = pageOf(catalog, query);
|
|
481
|
+
sendJson(res, 200, { ok: true, ...page });
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
module.exports = {
|
|
485
|
+
handlePluginCatalog,
|
|
486
|
+
// 纯逻辑(守卫 / 测试直接加载)
|
|
487
|
+
parseQuery,
|
|
488
|
+
pageOf,
|
|
489
|
+
narrowCatalog,
|
|
490
|
+
normalizeItem,
|
|
491
|
+
loadCatalog,
|
|
492
|
+
SOURCES,
|
|
493
|
+
CACHE_TTL_MS,
|
|
494
|
+
LIMIT_DEFAULT,
|
|
495
|
+
LIMIT_MAX,
|
|
496
|
+
Q_MAX_CHARS,
|
|
497
|
+
// 测试注入:假 fetch / 假时钟 / 清缓存(真跑时一个都不该被调用)
|
|
498
|
+
__setFetchForTests(next) { fetchImpl = next || null; },
|
|
499
|
+
__setClockForTests(next) { clock = next || null; },
|
|
500
|
+
__resetForTests() { cache = null; inflight = null; fetchImpl = null; clock = null; },
|
|
501
|
+
};
|