dsh-pick 0.4.4 → 0.5.1

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/boards.js ADDED
@@ -0,0 +1,156 @@
1
+ // lib/boards.js — npm、GitHub 之外的榜单数据
2
+ //
3
+ // official DeepSeek 官方包 @deepseek-ai/dsh-official-bundles 列出的可选 / 按需插件
4
+ // community awesome-dsh-plugin 社区目录(dshmarket 用的也是它):有星标、30 天下载、收录日期
5
+ // shop dsh-plugin-shop 的目录(第三方,不是 DeepSeek 官方):有星标、收录日期,没有下载量
6
+ //
7
+ // 每日构建时抓一次,只存每个榜的头部(整份目录有几十 MB,界面用不上)。这些都是别人维护的外部数据,
8
+ // 所以只摘需要的字段、校验类型和链接;官方包只按文本解析,绝不执行从网上下载的代码。
9
+
10
+ const OFFICIAL_JS = 'https://cdn.jsdelivr.net/npm/@deepseek-ai/dsh-official-bundles@latest/lib/index.js'
11
+ const COMMUNITY_URL = 'https://awesome-dsh-plugin.com/plugins.json'
12
+ const SHOP_BASE = 'https://LivXue.github.io/dsh-plugin-shop/v1/'
13
+ const REGISTRY = 'https://registry.npmjs.org/'
14
+ const DOWNLOADS = 'https://api.npmjs.org/downloads/point/last-week/'
15
+ const TOP = 100
16
+
17
+ const text = (v, max = 120) => (typeof v === 'string' ? v.trim().slice(0, max) : '')
18
+ const count = v => (Number.isFinite(v) && v >= 0 ? v : null)
19
+ const date = v => (/^\d{4}-\d{2}-\d{2}/.test(String(v || '')) ? String(v).slice(0, 10) : null)
20
+ const npmName = v => (typeof v === 'string' && /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(v) ? v : null)
21
+ /** 只留 https 的代码托管地址:链接要放进页面,别的协议和站点一律不要 */
22
+ const repoUrl = v => {
23
+ const m = /^https:\/\/(github\.com|gitlab\.com)\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/.exec(String(v || ''))
24
+ return m ? m[0].replace(/\.git$/, '') : null
25
+ }
26
+ const zh = v => (v && typeof v === 'object' ? text(v.zh) || text(v.en) : text(v))
27
+
28
+ /** 仓库填成 DSH 本体的,星标不算在插件头上(同 github.js 的 countsForPlugin) */
29
+ const ownStars = (stars, repo) => (/github\.com\/deepseek-ai\//i.test(String(repo || '')) ? null : stars)
30
+
31
+ /** 每个指标各取头部,合并去重:换个排序也有足够的数据 */
32
+ function topRows(rows, metrics) {
33
+ const keep = new Set()
34
+ for (const by of metrics) {
35
+ rows.filter(r => r[by] != null).sort((a, b) => (b[by] > a[by] ? 1 : b[by] < a[by] ? -1 : 0)).slice(0, TOP).forEach(r => keep.add(r))
36
+ }
37
+ return [...keep]
38
+ }
39
+
40
+ /** 从官方包的 JS 文本里摘出插件列表(只解析,不执行) */
41
+ export function parseOfficial(source) {
42
+ const src = String(source || '')
43
+ const out = new Map()
44
+ const optional = /OPTIONAL_BUNDLES\s*=\s*\[([\s\S]*?)\]/.exec(src)
45
+ if (optional) {
46
+ for (const m of optional[1].matchAll(/"([^"]+)"/g)) {
47
+ if (npmName(m[1])) out.set(m[1], { n: m[1], kind: 'optional', t: '', d: '' })
48
+ }
49
+ }
50
+ const start = src.search(/OFFICIAL_ON_DEMAND_CATALOG\s*=\s*\[/)
51
+ if (start >= 0) {
52
+ const parts = src.slice(start).split(/packageName:\s*/).slice(1)
53
+ for (const part of parts) {
54
+ const name = /^"([^"]+)"/.exec(part)
55
+ if (!name || !npmName(name[1])) continue
56
+ const zhOf = key => {
57
+ const block = new RegExp(`${key}:\\s*\\{([\\s\\S]*?)\\}`).exec(part)
58
+ const m = block && /"zh":\s*"((?:[^"\\]|\\.)*)"/.exec(block[1])
59
+ return m ? text(m[1]) : ''
60
+ }
61
+ out.set(name[1], { n: name[1], kind: 'ondemand', t: zhOf('title'), d: zhOf('description') })
62
+ }
63
+ }
64
+ return [...out.values()]
65
+ }
66
+
67
+ /** 社区目录 → 榜单 */
68
+ export function communityBoard(doc) {
69
+ const list = doc && Array.isArray(doc.plugins) ? doc.plugins : []
70
+ const rows = list.map(p => ({
71
+ n: npmName(p && p.npm),
72
+ name: text(p && p.name, 80),
73
+ repo: repoUrl(p && p.url),
74
+ s: ownStars(count(p && p.stars), repoUrl(p && p.url)),
75
+ dl: count(p && p.downloads),
76
+ added: date(p && p.added),
77
+ d: zh(p && p.description),
78
+ })).filter(r => r.name && (r.n || r.repo))
79
+ return { total: rows.length, updated: date(doc && doc.updated), rows: topRows(rows, ['s', 'dl', 'added']) }
80
+ }
81
+
82
+ /** 插件商店的目录 + 星标表 → 榜单。星标表按 owner/repo 或包名记 */
83
+ export function shopBoard(plugins, stars) {
84
+ const list = Array.isArray(plugins) ? plugins : (plugins && plugins.plugins) || []
85
+ const table = (stars && stars.stars) || stars || {}
86
+ const rows = list.map(p => {
87
+ const repo = repoUrl(p && p.repository)
88
+ const key = repo ? repo.replace(/^https:\/\/[^/]+\//, '') : ''
89
+ return {
90
+ n: p && p.source === 'npm' ? npmName(p.name) : null,
91
+ name: text(p && p.name, 80),
92
+ repo,
93
+ s: ownStars(count(table[key] ?? table[p && p.name]), repo),
94
+ added: date(p && p.added),
95
+ d: zh(p && p.catalog && p.catalog.summary),
96
+ }
97
+ }).filter(r => r.name && (r.n || r.repo))
98
+ return { total: rows.length, rows: topRows(rows, ['s', 'added']) }
99
+ }
100
+
101
+ async function getJson(fetchImpl, url, ms) {
102
+ const r = await fetchImpl(url, { signal: AbortSignal.timeout(ms), headers: { accept: 'application/json' } })
103
+ if (!r.ok) throw new Error(`HTTP ${r.status}`)
104
+ return r.json()
105
+ }
106
+
107
+ async function loadOfficial(fetchImpl) {
108
+ const r = await fetchImpl(OFFICIAL_JS, { signal: AbortSignal.timeout(30000) })
109
+ if (!r.ok) throw new Error(`HTTP ${r.status}`)
110
+ const rows = parseOfficial(await r.text())
111
+ if (!rows.length) throw new Error('官方包里没解析出插件')
112
+ await Promise.all(rows.map(async row => {
113
+ const enc = row.n.replace('/', '%2f')
114
+ const [meta, dl] = await Promise.all([
115
+ getJson(fetchImpl, `${REGISTRY}${enc}/latest`, 15000).catch(() => null),
116
+ getJson(fetchImpl, `${DOWNLOADS}${enc}`, 15000).catch(() => null),
117
+ ])
118
+ row.v = meta ? text(meta.version, 40) : ''
119
+ if (!row.d && meta) row.d = text(meta.description)
120
+ row.w = dl ? count(dl.downloads) : null
121
+ }))
122
+ return { total: rows.length, rows }
123
+ }
124
+
125
+ async function loadShop(fetchImpl) {
126
+ const index = await getJson(fetchImpl, `${SHOP_BASE}index.json`, 30000)
127
+ const [plugins, stars] = await Promise.all([
128
+ getJson(fetchImpl, SHOP_BASE + index.plugins.url, 180000),
129
+ getJson(fetchImpl, SHOP_BASE + index.stars.url, 60000),
130
+ ])
131
+ return shopBoard(plugins, stars)
132
+ }
133
+
134
+ /**
135
+ * 抓全部榜单。某个来源这次抓不到,就沿用上次的那份,不让一个榜拖垮整个构建
136
+ * @param {object} [opt]
137
+ * @param {object} [opt.previous] 上一次的 boards
138
+ */
139
+ export async function buildBoards({ fetchImpl = globalThis.fetch, previous = {}, onProgress = () => {} } = {}) {
140
+ const sources = {
141
+ official: () => loadOfficial(fetchImpl),
142
+ community: async () => communityBoard(await getJson(fetchImpl, COMMUNITY_URL, 180000)),
143
+ shop: () => loadShop(fetchImpl),
144
+ }
145
+ const boards = {}
146
+ for (const [key, load] of Object.entries(sources)) {
147
+ try {
148
+ boards[key] = await load()
149
+ onProgress(` 榜单 ${key}:共 ${boards[key].total} 个,保留 ${boards[key].rows.length} 行`)
150
+ } catch (e) {
151
+ onProgress(` 榜单 ${key} 抓不到(${e.message}),沿用上次的`)
152
+ if (previous && previous[key]) boards[key] = previous[key]
153
+ }
154
+ }
155
+ return boards
156
+ }
package/lib/engine.js CHANGED
@@ -12,6 +12,8 @@ import { fileURLToPath } from 'node:url'
12
12
  import { classify } from './classify.js'
13
13
  import { expandWords } from './words.js'
14
14
  import { baselineWithStart, growth, cadence, ageDays, score, sum } from './metrics.js'
15
+ import { parseRepo, fetchRepos, fetchRepoLive, countsForPlugin } from './github.js'
16
+ import { buildBoards } from './boards.js'
15
17
 
16
18
  const PKG_ROOT = fileURLToPath(new URL('..', import.meta.url))
17
19
  /** 随包自带的目录(发版时的快照;dsh-pick build 也写这里) */
@@ -73,12 +75,37 @@ const shiftDate = (iso, d) => {
73
75
  return t.toISOString().slice(0, 10)
74
76
  }
75
77
 
76
- /** npm 统计滞后约 5 天,先探测最后一个已汇总的完整日 */
77
- async function resolveAnchor() {
78
- const probe = await jget(`${DL_API}/point/last-day/dsh-market`)
79
- return (probe && probe.end) || shiftDate(new Date().toISOString().slice(0, 10), -5)
78
+ /**
79
+ * npm 下载统计最后一个已汇总的完整日。拿 react 探:全 npm 下载最多的包之一,哪天有数据它一定有。
80
+ * (以前探的是 dsh-market——这个包根本不存在,每次都退回「今天减 5 天」的估算)
81
+ */
82
+ export async function resolveAnchor() {
83
+ for (const probe of ['react', 'dshmarket']) {
84
+ const d = await jget(`${DL_API}/point/last-day/${probe}`, 2)
85
+ if (d && /^\d{4}-\d{2}-\d{2}$/.test(String(d.end || '')) && d.downloads > 0) return d.end
86
+ }
87
+ return shiftDate(new Date().toISOString().slice(0, 10), -5)
88
+ }
89
+
90
+ /**
91
+ * npm 自己缺数据的日子:react 那天下载量是 0,就说明 npm 那天的统计没出来(2026-10 实测连着缺过 3 天),
92
+ * 不是真的没人下载。返回窗口内的下标集合;这些天在日序列里记成 null,不参与基线、环比的计算。
93
+ * 探测失败就当没有缺口(宁可少剔,不乱剔)
94
+ */
95
+ const gapCache = new Map()
96
+ export async function gapDays(start, anchor) {
97
+ const key = `${start}:${anchor}`
98
+ if (gapCache.has(key)) return gapCache.get(key)
99
+ const r = await jget(`${DL_API}/range/${start}:${anchor}/react`, 3)
100
+ const gaps = new Set()
101
+ if (r && Array.isArray(r.downloads)) r.downloads.forEach((x, i) => { if (!x.downloads) gaps.add(i) })
102
+ gapCache.set(key, gaps)
103
+ return gaps
80
104
  }
81
105
 
106
+ /** 日序列里把 npm 缺数据的日子换成 null */
107
+ export const maskGaps = (daily, gaps) => daily.map((v, i) => (gaps.has(i) ? null : v))
108
+
82
109
  /* ---------------------------------------------------------------- 目录构建 */
83
110
 
84
111
  /**
@@ -89,11 +116,13 @@ async function resolveAnchor() {
89
116
  * @param {boolean} opt.deepOnly 只补算去噪指标,不重新抓目录(省 5 分钟)
90
117
  * @param {(msg:string)=>void} opt.onProgress 进度回调
91
118
  */
92
- export async function buildCatalog({ deep = 200, max = 2250, pages = 9, deepOnly = false, onProgress = () => {} } = {}) {
119
+ export async function buildCatalog({ deep = 200, max = 2250, pages = 9, deepOnly = false, githubToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN, onProgress = () => {} } = {}) {
93
120
  const today = new Date().toISOString().slice(0, 10)
94
121
  const anchor = await resolveAnchor()
95
122
  const start = shiftDate(anchor, -29)
96
- onProgress(`统计截止日 ${anchor},${deepOnly ? '只补算去噪指标' : '开始抓取目录'}…`)
123
+ const gaps = await gapDays(start, anchor)
124
+ const gapDates = [...gaps].sort((a, b) => a - b).map(i => shiftDate(start, i))
125
+ onProgress(`统计截止日 ${anchor}${gapDates.length ? `;npm 缺 ${gapDates.join('、')} 的数据,这几天不参与计算` : ''},${deepOnly ? '只补算去噪指标' : '开始抓取目录'}…`)
97
126
 
98
127
  const records = new Map()
99
128
 
@@ -166,7 +195,7 @@ export async function buildCatalog({ deep = 200, max = 2250, pages = 9, deepOnly
166
195
  onProgress(` 发布历史 ${ok.length} 个…`)
167
196
  const metas = await pool(ok, 8, async rec => jget(`${REG_API}/${enc(rec.n)}`))
168
197
  ok.forEach((rec, i) => {
169
- const daily = ranges[pending.indexOf(rec)]
198
+ const daily = maskGaps(ranges[pending.indexOf(rec)], gaps)
170
199
  const meta = metas[i]
171
200
  const releaseDates = (meta && meta.time)
172
201
  ? Object.entries(meta.time)
@@ -208,11 +237,40 @@ export async function buildCatalog({ deep = 200, max = 2250, pages = 9, deepOnly
208
237
  const manifests = await pool(needFacts, 8, rec => jget(`${REG_API}/${enc(rec.n)}/latest`, 2))
209
238
  needFacts.forEach((rec, i) => { if (manifests[i]) rec.inst = installFacts(manifests[i]) })
210
239
 
240
+ // GitHub:星标、Fork、未关闭 issue / PR、最近提交、归档。要令牌(Actions 自带的就够),没有就跳过
241
+ if (githubToken) {
242
+ // 指向 DSH 本体的仓库不算(见 countsForPlugin)
243
+ const repoOf = rec => {
244
+ const repo = parseRepo(rec.repo) || parseRepo(rec.home)
245
+ return countsForPlugin(rec.n, repo) ? repo : null
246
+ }
247
+ const repos = [...records.values()].map(repoOf).filter(Boolean)
248
+ onProgress(`GitHub 仓库数据 ${new Set(repos.map(r => r.toLowerCase())).size} 个…`)
249
+ const found = await fetchRepos(repos, { token: githubToken, onProgress })
250
+ for (const rec of records.values()) {
251
+ const repo = repoOf(rec)
252
+ const g = repo && found.get(repo.toLowerCase())
253
+ if (g) rec.gh = g
254
+ else if (!deepOnly) delete rec.gh
255
+ }
256
+ onProgress(` GitHub 查到 ${found.size} 个仓库`)
257
+ } else {
258
+ onProgress('没设 GITHUB_TOKEN,跳过 GitHub 数据(GitHub Actions 里会自动带上)')
259
+ }
260
+
261
+ // npm、GitHub 之外的榜单:官方、社区、插件商店(抓不到的沿用上次)
262
+ onProgress('其他榜单…')
263
+ const previous = await readJson(CATALOG_PATH)
264
+ const boards = await buildBoards({ previous: previous && previous.boards, onProgress })
265
+
211
266
  const catalog = {
212
267
  tool: 'dsh-pick',
213
268
  asOf: today,
214
269
  anchor,
215
270
  windowStart: start,
271
+ gaps: gapDates,
272
+ githubCount: [...records.values()].filter(r => r.gh).length,
273
+ boards,
216
274
  total: records.size,
217
275
  deepCount: [...records.values()].filter(r => r.deep).length,
218
276
  packages: Object.fromEntries([...records.entries()]),
@@ -311,7 +369,8 @@ export function normalize(cat) {
311
369
  r.repoUrl = repo
312
370
  // GitHub 地址优先取 repo,其次 homepage(很多包装配的是 github.io)
313
371
  const gh = (repo || r.home || '')
314
- r.ghUrl = /github\.com/.test(gh) ? gh : ''
372
+ // 链接要放进页面:只认 https?:// 开头的 GitHub 地址
373
+ r.ghUrl = /^https?:\/\/([^/]*\.)?github\.com\//.test(gh) ? gh : ''
315
374
  }
316
375
 
317
376
  return cat
@@ -373,8 +432,22 @@ export function rank(catalog, { metric = 'weekly', category = null, limit = 50,
373
432
  const val = r => metric === 'score' ? (r.deep ? r.deep.s : -1)
374
433
  : metric === 'baseline' ? (r.deep ? r.deep.base : -1)
375
434
  : metric === 'growth' ? (r.deep && r.deep.growth !== null ? r.deep.growth : -Infinity)
376
- : metric === 'monthly' ? r.m : r.w
435
+ : metric === 'monthly' ? r.m
436
+ : metric === 'stars' ? (r.gh ? r.gh.s : -1)
437
+ : metric === 'pushed' ? (r.gh && r.gh.p ? Date.parse(r.gh.p) : -Infinity)
438
+ : r.w
377
439
  all.sort((a, b) => val(b) - val(a))
440
+ // 按 GitHub 排时一个仓库只留一行(周下载最多的那个插件),不然同仓库的一串插件数据一模一样、刷屏
441
+ if (metric === 'stars' || metric === 'pushed') {
442
+ const best = new Map()
443
+ for (const r of all) {
444
+ if (!r.gh) continue
445
+ const k = r.gh.repo.toLowerCase()
446
+ if (!best.has(k) || r.w > best.get(k).w) best.set(k, r)
447
+ }
448
+ const keep = new Set(best.values())
449
+ return all.filter(r => keep.has(r)).slice(from, from + limit)
450
+ }
378
451
  return all.slice(from, from + limit)
379
452
  }
380
453
 
@@ -399,19 +472,56 @@ export async function stats(catalog, names) {
399
472
  * 不带 30 天日序列(太长,界面用不上)
400
473
  * @returns {Promise<{at: string, anchor: string, rows: object[]}>}
401
474
  */
402
- export async function liveStats(names) {
475
+ /**
476
+ * 监控列表里的名字:npm 包名,或只在 GitHub 上的插件 gh:owner/repo。
477
+ * 从查询串里取出合法的、去重,最多 30 个
478
+ */
479
+ export function parseWatchNames(url) {
480
+ const raw = new URL(url || '/', 'http://x').searchParams.get('names') || ''
481
+ const ok = s => /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(s) || /^gh:[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(s)
482
+ return [...new Set(raw.split(',').map(s => s.trim()).filter(ok))].slice(0, 30)
483
+ }
484
+
485
+ export async function liveStats(allNames, { fetchImpl } = {}) {
486
+ const repoOnly = allNames.filter(n => n.startsWith('gh:'))
487
+ const names = allNames.filter(n => !n.startsWith('gh:'))
403
488
  const anchor = await resolveAnchor()
489
+ const cat = await loadCatalog()
490
+ // GitHub:按目录里登记的仓库实时查(同一个仓库只查一次);被限流就整批放弃,说清楚原因
491
+ const repoOf = n => {
492
+ const rec = cat.packages[n]
493
+ const repo = rec ? parseRepo(rec.ghUrl || rec.repo || rec.home) : null
494
+ return countsForPlugin(n, repo) ? repo : null
495
+ }
496
+ const repos = [...new Set([...names.map(repoOf).filter(Boolean), ...repoOnly.map(n => n.slice(3))])]
497
+ const ghLive = new Map()
498
+ let githubError = null
499
+ await pool(repos, 4, async repo => {
500
+ if (githubError) return
501
+ try {
502
+ const g = await fetchRepoLive(repo, fetchImpl ? { fetchImpl } : {})
503
+ if (g) ghLive.set(repo, g)
504
+ } catch (e) {
505
+ githubError = e.code === 'rate-limited' ? e.message : `GitHub 查不到:${e.message}`
506
+ }
507
+ })
404
508
  const rows = await pool(names, 2, async name => {
405
509
  const [r, dl] = await Promise.all([fetchLive(name, anchor), searchDownloads(name)])
406
510
  if (!r && !dl) return { name, found: false }
407
511
  const { daily, keywords, ...rest } = r || { name, deep: null }
408
512
  // 周下载 / 月下载用搜索接口的:和目录同一口径(目录就是从它抓的),而且比下载统计接口新——
409
513
  // 下载统计接口常常只到几天前,拿它和目录比会凭空「跌」一截
514
+ const gh = ghLive.get(repoOf(name)) || null
410
515
  return dl
411
- ? { found: true, ...rest, weekly: dl.weekly, monthly: dl.monthly, latest: rest.latest || dl.version }
412
- : { found: true, ...rest }
516
+ ? { found: true, ...rest, weekly: dl.weekly, monthly: dl.monthly, latest: rest.latest || dl.version, gh }
517
+ : { found: true, ...rest, gh }
413
518
  })
414
- return { at: new Date().toISOString(), anchor, rows }
519
+ // 只在 GitHub 上的插件:没有 npm 数据,只有仓库数据
520
+ for (const name of repoOnly) {
521
+ const gh = ghLive.get(name.slice(3))
522
+ rows.push(gh ? { found: true, name, gh, deep: null } : { found: false, name })
523
+ }
524
+ return { at: new Date().toISOString(), anchor, rows, githubError }
415
525
  }
416
526
 
417
527
  /** npm 搜索接口里这个包的周 / 月下载(按包名精确匹配;查不到返回 null) */
@@ -432,7 +542,7 @@ async function fetchLive(name, knownAnchor) {
432
542
  ])
433
543
  if (!range || !Array.isArray(range.downloads) || !range.downloads.length) return null
434
544
 
435
- const daily = range.downloads.map(x => x.downloads)
545
+ const daily = maskGaps(range.downloads.map(x => x.downloads), await gapDays(start, anchor))
436
546
  let releaseDates = []
437
547
  if (meta && meta.time) {
438
548
  releaseDates = Object.entries(meta.time)
package/lib/github.js ADDED
@@ -0,0 +1,123 @@
1
+ // lib/github.js — 插件仓库在 GitHub 上的数据
2
+ //
3
+ // npm 下载量回答「多少人在拉」,GitHub 回答「维护得怎么样」:星标、Fork、未关闭的 issue / PR、
4
+ // 最近一次提交、是不是已经归档。两边合起来判断才靠谱。
5
+ //
6
+ // 两种取法:
7
+ // - 每日构建(GitHub Actions):GraphQL 一次查 50 个仓库,2,000 个仓库几十次请求就完。要令牌:
8
+ // Actions 里自带的 GITHUB_TOKEN 就够;本地 build 没设 GITHUB_TOKEN 就跳过这一步
9
+ // - 「我的监控」刷新:REST 逐个查,不用令牌(每小时 60 次,监控列表最多 30 个,够用)
10
+ //
11
+ // 存进目录的字段名短(2,000 多个包都要存):
12
+ // s 星标 · f Fork · i 未关闭的 issue + PR · p 最近一次提交(YYYY-MM-DD)· a 已归档 · l 许可证 · repo owner/name
13
+
14
+ const GRAPHQL = 'https://api.github.com/graphql'
15
+ const REST = 'https://api.github.com/repos/'
16
+ const BATCH = 50
17
+
18
+ /** 从各种写法的仓库地址里取出 owner/name;不是 GitHub 仓库返回 null */
19
+ export function parseRepo(url) {
20
+ const m = /github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/.exec(String(url || ''))
21
+ if (!m) return null
22
+ const name = m[2].replace(/\.git$/, '')
23
+ if (!name || name === '.' || name === '..') return null
24
+ return `${m[1]}/${name}`
25
+ }
26
+
27
+ const day = iso => (iso ? String(iso).slice(0, 10) : null)
28
+
29
+ /**
30
+ * 这个仓库的星标能不能算在插件头上。DSH 本体(deepseek-ai/ 下的仓库)不能:
31
+ * 实测有插件把 repository 填成 deepseek-ai/deepseek-harness,凭空「拥有」25 万星。
32
+ * DeepSeek 官方自己的包(@deepseek-ai/ 下)例外
33
+ */
34
+ export function countsForPlugin(pkgName, repo) {
35
+ if (!repo) return false
36
+ const owner = repo.split('/')[0].toLowerCase()
37
+ return owner !== 'deepseek-ai' || String(pkgName).startsWith('@deepseek-ai/')
38
+ }
39
+
40
+ function fromGraphql(r, repo) {
41
+ return {
42
+ repo,
43
+ s: r.stargazerCount,
44
+ f: r.forkCount,
45
+ i: (r.issues ? r.issues.totalCount : 0) + (r.pullRequests ? r.pullRequests.totalCount : 0),
46
+ p: day(r.pushedAt),
47
+ a: Boolean(r.isArchived),
48
+ l: (r.licenseInfo && r.licenseInfo.spdxId) || null,
49
+ }
50
+ }
51
+
52
+ /** GraphQL 字符串字面量:仓库名只含 [A-Za-z0-9_.-](parseRepo 保证),这里再转义一次防万一 */
53
+ const lit = s => JSON.stringify(String(s))
54
+
55
+ /**
56
+ * 批量查仓库(每日构建用)
57
+ * @param {string[]} repos owner/name 列表(会去重)
58
+ * @returns {Promise<Map<string, object>>} 小写的 owner/name → 数据;查不到的不在里面
59
+ */
60
+ export async function fetchRepos(repos, { token, fetchImpl = globalThis.fetch, onProgress = () => {} } = {}) {
61
+ const out = new Map()
62
+ if (!token) return out
63
+ // 去重不分大小写(GitHub 仓库名不分),保留第一次出现的写法
64
+ const seen = new Map()
65
+ for (const r of repos) if (r && !seen.has(r.toLowerCase())) seen.set(r.toLowerCase(), r)
66
+ const unique = [...seen.values()]
67
+ for (let i = 0; i < unique.length; i += BATCH) {
68
+ const batch = unique.slice(i, i + BATCH)
69
+ const fields = 'stargazerCount forkCount isArchived pushedAt licenseInfo { spdxId } issues(states: OPEN) { totalCount } pullRequests(states: OPEN) { totalCount }'
70
+ const query = '{' + batch.map((repo, k) => {
71
+ const [owner, name] = repo.split('/')
72
+ return `r${k}: repository(owner: ${lit(owner)}, name: ${lit(name)}) { ${fields} }`
73
+ }).join(' ') + '}'
74
+ for (let attempt = 1; attempt <= 3; attempt++) {
75
+ try {
76
+ const res = await fetchImpl(GRAPHQL, {
77
+ method: 'POST',
78
+ headers: { authorization: `bearer ${token}`, 'content-type': 'application/json', 'user-agent': 'dsh-pick' },
79
+ body: JSON.stringify({ query }),
80
+ signal: AbortSignal.timeout(30000),
81
+ })
82
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
83
+ const j = await res.json()
84
+ // 仓库删了 / 改名 / 私有:那一项是 null,errors 里有说明,别的照常
85
+ batch.forEach((repo, k) => {
86
+ const r = j.data && j.data[`r${k}`]
87
+ if (r) out.set(repo.toLowerCase(), fromGraphql(r, repo))
88
+ })
89
+ break
90
+ } catch (e) {
91
+ if (attempt === 3) onProgress(` GitHub 第 ${i / BATCH + 1} 批查不到:${e.message}`)
92
+ else await new Promise(r => setTimeout(r, 1500 * attempt))
93
+ }
94
+ }
95
+ onProgress(` GitHub ${Math.min(i + BATCH, unique.length)} / ${unique.length}…`)
96
+ }
97
+ return out
98
+ }
99
+
100
+ /**
101
+ * 实时查一个仓库(「我的监控」刷新用,不要令牌)
102
+ * @returns {Promise<object|null>} 查不到返回 null;被限流抛出 code = 'rate-limited' 的错
103
+ */
104
+ export async function fetchRepoLive(repo, { fetchImpl = globalThis.fetch, token } = {}) {
105
+ const headers = { accept: 'application/vnd.github+json', 'user-agent': 'dsh-pick' }
106
+ if (token) headers.authorization = `bearer ${token}`
107
+ const res = await fetchImpl(REST + repo, { headers, signal: AbortSignal.timeout(10000) })
108
+ if (res.status === 403 || res.status === 429) {
109
+ throw Object.assign(new Error('GitHub 限流了(不登录每小时 60 次),过一会儿再刷新'), { code: 'rate-limited' })
110
+ }
111
+ if (!res.ok) return null
112
+ const r = await res.json()
113
+ return {
114
+ repo: r.full_name || repo,
115
+ s: r.stargazers_count,
116
+ f: r.forks_count,
117
+ // REST 的 open_issues_count 本来就包含未关闭的 PR,和 GraphQL 那边加起来的口径一致
118
+ i: r.open_issues_count,
119
+ p: day(r.pushed_at),
120
+ a: Boolean(r.archived),
121
+ l: (r.license && r.license.spdx_id && r.license.spdx_id !== 'NOASSERTION') ? r.license.spdx_id : null,
122
+ }
123
+ }
package/lib/metrics.js CHANGED
@@ -20,7 +20,7 @@ export function mean(arr) {
20
20
 
21
21
  export function sum(arr) {
22
22
  if (!arr || !arr.length) return 0
23
- return arr.reduce((x, y) => x + y, 0)
23
+ return arr.reduce((x, y) => x + (y || 0), 0)
24
24
  }
25
25
 
26
26
  const dayMs = 86400000
@@ -36,8 +36,10 @@ const toDay = iso => Math.floor(new Date(iso + 'T00:00:00Z').getTime() / dayMs)
36
36
  * @returns {number}
37
37
  */
38
38
  export function baselineWithStart(daily = [], releaseDates = [], startISO = '') {
39
- if (!daily.length) return 0
40
- if (!releaseDates.length || !startISO) return median(daily)
39
+ // null = npm 那天没有数据(全网都是 0 的日子,见 engine.js 的 gapDays):不算进中位数
40
+ const valid = daily.filter(v => v != null)
41
+ if (!valid.length) return 0
42
+ if (!releaseDates.length || !startISO) return median(valid)
41
43
 
42
44
  const spikes = new Set()
43
45
  const s = toDay(startISO)
@@ -48,8 +50,8 @@ export function baselineWithStart(daily = [], releaseDates = [], startISO = '')
48
50
  spikes.add(n - s + 1) // 发布次日
49
51
  }
50
52
  }
51
- const kept = daily.filter((_, i) => !spikes.has(i))
52
- return kept.length >= 5 ? median(kept) : median(daily)
53
+ const kept = daily.filter((v, i) => v != null && !spikes.has(i))
54
+ return kept.length >= 5 ? median(kept) : median(valid)
53
55
  }
54
56
 
55
57
  /**
@@ -58,9 +60,11 @@ export function baselineWithStart(daily = [], releaseDates = [], startISO = '')
58
60
  * @returns {number|null}
59
61
  */
60
62
  export function growth(daily = []) {
61
- if (daily.length < 14) return null
62
- const last7 = sum(daily.slice(-7))
63
- const prev7 = sum(daily.slice(-14, -7))
63
+ // 只用 npm 有数据的日子:缺数据的天当 0 算,会凭空算出「暴跌 / 暴涨」
64
+ const valid = daily.filter(v => v != null)
65
+ if (valid.length < 14) return null
66
+ const last7 = sum(valid.slice(-7))
67
+ const prev7 = sum(valid.slice(-14, -7))
64
68
  if (prev7 === 0) return last7 > 0 ? 1 : null
65
69
  return (last7 - prev7) / prev7
66
70
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-pick",
3
- "version": "0.4.4",
3
+ "version": "0.5.1",
4
4
  "description": "帮你在 DSH 生态里选对插件:说需求 → 找候选 → 多维比较 → 出结论。下载量是证据,AI 是推理。",
5
5
  "repository": {
6
6
  "type": "git",
package/plugin/client.js CHANGED
@@ -249,7 +249,7 @@ window.__ModuleLoader__.load({
249
249
  // 数据口径说明:面板底部原来那段,现在放在设置页
250
250
  const DATA_NOTE = () => L(
251
251
  '排名按周下载;日常基线已扣掉版本发布日与次日的拉取虚高,比原始下载量更接近真实使用量。' +
252
- '下载量含 CI / 镜像 / 爬虫流量,不等于用户数。npm 统计约滞后 5 天。',
252
+ '下载量含 CI / 镜像 / 爬虫流量,不等于用户数。npm 的每日下载只在一天结束后汇总,最近常晚几天。',
253
253
  'Ranks are weekly downloads; daily baseline strips the publish-day spike and is closer to real use. ' +
254
254
  'Download counts include CI/mirror/crawler traffic, not real users. npm stats lag about 5 days.')
255
255
 
package/plugin/index.js CHANGED
@@ -25,7 +25,7 @@ import { readFile } from 'node:fs/promises'
25
25
  import { fileURLToPath } from 'node:url'
26
26
  import { join } from 'node:path'
27
27
  import { registerTools } from './tools.js'
28
- import { loadCatalog, liveStats } from '../lib/engine.js'
28
+ import { loadCatalog, liveStats, parseWatchNames } from '../lib/engine.js'
29
29
  import { refreshCatalog, remoteState, CHECK_EVERY_MS } from '../lib/remote.js'
30
30
 
31
31
  /** 本包根目录:插件就是完整的 dsh-pick 包 */
@@ -142,10 +142,13 @@ function readJsonBody(req) {
142
142
  })
143
143
  }
144
144
 
145
- /** DSH 插件管理器清单里已装、已启用的插件名;拿不到就是 null(老版本 DSH) */
146
- function installedNames(pluginManager) {
145
+ /**
146
+ * DSH 插件管理器清单里已装的插件名;拿不到就是 null(老版本 DSH)。
147
+ * 新版 DSH 的 listBundles 返回 Promise,老版本直接返回数组,两种都要认
148
+ */
149
+ async function installedNames(pluginManager) {
147
150
  try {
148
- const list = pluginManager && typeof pluginManager.listBundles === 'function' ? pluginManager.listBundles() : null
151
+ const list = pluginManager && typeof pluginManager.listBundles === 'function' ? await pluginManager.listBundles() : null
149
152
  if (!Array.isArray(list)) return null
150
153
  return new Set(list.filter(b => b && b.name && b.installed !== false).map(b => b.name))
151
154
  } catch {
@@ -155,11 +158,6 @@ function installedNames(pluginManager) {
155
158
 
156
159
  const NAME_RE = /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i
157
160
 
158
- /** ?names=a,b,c → 合法、去重的包名,最多 30 个(监控列表本身也最多 30 个) */
159
- export function parseNames(url) {
160
- const raw = new URL(url || '/', 'http://x').searchParams.get('names') || ''
161
- return [...new Set(raw.split(',').map(s => s.trim()).filter(s => NAME_RE.test(s)))].slice(0, 30)
162
- }
163
161
 
164
162
  function sendJson(res, status, body) {
165
163
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
@@ -238,7 +236,7 @@ export function apply(ctx) {
238
236
  ctx.inject(['tools'], (toolsCtx) => {
239
237
  const tools = toolsCtx.tools || (toolsCtx.get && toolsCtx.get('tools'))
240
238
  if (!tools || typeof tools.register !== 'function') return
241
- registerTools({ tools }, { installed: () => installedNames(pluginManager) || new Set() })
239
+ registerTools({ tools }, { installed: async () => (await installedNames(pluginManager)) || new Set() })
242
240
  .catch(e => console.warn('[dsh-pick] AI 工具注册失败', e))
243
241
  })
244
242
 
@@ -358,7 +356,7 @@ export function apply(ctx) {
358
356
  kind: 'exact',
359
357
  path: '/api-dsh-pick/live',
360
358
  handler: async (req, res) => {
361
- const names = parseNames(req.url)
359
+ const names = parseWatchNames(req.url)
362
360
  if (!names.length) return sendJson(res, 400, { error: '没有合法的包名' })
363
361
  try {
364
362
  sendJson(res, 200, await liveStats(names))
@@ -373,7 +371,7 @@ export function apply(ctx) {
373
371
  kind: 'exact',
374
372
  path: '/api-dsh-pick/installed',
375
373
  handler: async (req, res) => {
376
- const names = installedNames(pluginManager)
374
+ const names = await installedNames(pluginManager)
377
375
  sendJson(res, 200, {
378
376
  known: Boolean(names),
379
377
  names: names ? [...names] : [],