dsh-aupdate 0.7.4 → 0.7.5

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 CHANGED
@@ -206,6 +206,28 @@ stargazers)与「分享」(复制项目地址到剪贴板,任何环境都
206
206
  一律 503。不用「只认回环地址」这种判据:浏览器里任何网页都能向 127.0.0.1 发请求。
207
207
  `/state` 和 `/logs` 也照样要过,因为它们分别会吐全量设置和读磁盘上的日志文件。
208
208
 
209
+ ## 版本管理
210
+
211
+ 「插件」页顶栏多了一个「版本管理」标签:列出每个已装插件、已装版本,以及该插件的全部已发布
212
+ 版本;点某一版就直接切过去。走的是和定时更新同一条安装路径——安装、回读磁盘上的版本、记一条
213
+ 更新记录、就地生效——所以切完能在「更新记录」里看到,也能再回滚回来。
214
+
215
+ 每个版本先和这台宿主的 DSH 版本比一次:装不了的版本标红、按钮禁用(宿主的闸门是在 bundle
216
+ 已经卸下之后才拒绝的,不能让它走到那一步)。版本列表按包按需拉,不进首屏:整页一次拉一排
217
+ 包的 packument,在镜像上会慢到没法用。
218
+
219
+ ## 安装源与兼容性预检
220
+
221
+ 设置页的「安装源」有三档预设加一个自定义:**跟随 pnpm**(默认,一个字节都不改)/ 官方源 /
222
+ 大陆镜像 / 自定义 `http(s)` 地址。选了之后,查版本和装包都走这个源;装包只把这个源写进
223
+ 子进程的 `npm_config_registry`,不动 `~/.npmrc`,也不改 pnpm 自己的配置。
224
+
225
+ 用了镜像就会顺手比一次官方源:「已经是最新」有可能只是镜像还没同步。落后的那些写进「上一次」
226
+ 卡片,按名字列出「镜像 x.y.z → 官方 a.b.c」。
227
+
228
+ 「装前检查 DSH 兼容性」默认开着:真要装某个版本之前,读一次该版本的 manifest(几 KB),按
229
+ `engines.dsh`(没有才看 `@deepseek-ai/dsh*` 的 peer)和当前宿主版本比一遍。装不了的不进
230
+ 安装队列,日志留一行。**读不到 DSH 版本时不拦**——宁可漏拦,也不要按猜的版本误拦。
209
231
  ## 更新提醒
210
232
 
211
233
  发现可更新版本时,界面右下角浮一条提醒,列出插件名和「当前 → 新」版本;超过 8 条
@@ -464,6 +486,34 @@ once and, like every other setting, is persisted immediately. The choice is stor
464
486
  `~/.dsh/aupdate-settings.json` (key `lang`), so another browser or machine opens the page
465
487
  in the same language. Wording only — it changes no update behaviour.
466
488
 
489
+ ## Version manager
490
+
491
+ The plugins page gains a **Versions** tab: it lists every installed plugin, the version you have,
492
+ and every published version of it. Click one and it switches. The switch uses the same install
493
+ path as the scheduled cycle — install, read the version back from disk, append a history row,
494
+ apply in place — so it shows up in Update history and can be rolled back again.
495
+
496
+ Each version is compared against this host's DSH version first: versions that cannot run here are
497
+ marked and their button disabled (the host's gate only refuses after the bundle is gone, so it
498
+ must not be allowed to get that far). Version lists are fetched per package on demand, never on
499
+ first paint: fetching packuments for a whole page of packages is unusably slow on a mirror.
500
+
501
+ ## Registry and compatibility pre-check
502
+
503
+ Under Settings, **Registry** has three presets plus a custom value: **Follow pnpm** (the default,
504
+ which changes nothing) / Official / China mirror / a custom `http(s)` URL. Once picked, both
505
+ version lookups and installs use it; an install only passes it to the child process as
506
+ `npm_config_registry`, so `~/.npmrc` and pnpm's own config are never touched.
507
+
508
+ When a mirror is in use the official registry is checked too, because "already up to date" may
509
+ only mean the mirror has not synced yet. Those are listed in the Last run card as
510
+ "mirror x.y.z → upstream a.b.c".
511
+
512
+ **Check DSH compatibility first** (on by default) reads the target version's manifest (a few KB)
513
+ before installing and compares `engines.dsh` (falling back to the `@deepseek-ai/dsh*` peer range)
514
+ against the running host. Unusable versions are kept out of the install queue and leave a log
515
+ line. When the DSH version cannot be read, **nothing is blocked** — a missed block is better than
516
+ blocking on a guessed version.
467
517
  ### Update notices
468
518
 
469
519
  When a check finds updates, a notice appears in the bottom-right corner listing each
package/client.js CHANGED
@@ -128,6 +128,41 @@ window.__ModuleLoader__.load({
128
128
  allowHint: '每行一个包名;留空表示全部包都参与',
129
129
  allowMajor: '允许跨大版本',
130
130
  allowMajorHint: '关闭后只在同一主版本内升级(0.x 插件多半会因此长期不动)',
131
+ registry: '安装源',
132
+ registryHint: '查版本和装包都走这个源。默认跟随 pnpm 自己的配置,一个字节都不改。',
133
+ regPnpm: '跟随 pnpm',
134
+ regNpmjs: '官方源',
135
+ regMirror: '大陆镜像',
136
+ regCustom: '自定义',
137
+ regUrl: '自定义源地址',
138
+ regUrlHint: 'http(s)://…;填的不是 http(s) 就退回「跟随 pnpm」',
139
+ compatCheck: '装前检查 DSH 兼容性',
140
+ compatCheckHint: '宿主是等插件卸下之后才拒绝装不上的版本的;提前拦下,快照不会白拍、也不会留下半装的样子',
141
+ dshVersion: 'DSH 版本',
142
+ lagTitle: '镜像落后',
143
+ lagNote: '{n} 个插件的镜像还没同步,官方源已经有新版本',
144
+ blockedNote: '{n} 个版本在这台 DSH 上装不了',
145
+ versionsTab: '版本管理',
146
+ versionsTitle: '版本管理',
147
+ versionsSubtitle: '每个已装插件的全部已发布版本,点一下就切过去',
148
+ versionsSearch: '搜索插件名',
149
+ versionsCount: '{n} 个插件',
150
+ versionsShow: '版本',
151
+ versionsHide: '收起',
152
+ versionsSwitch: '切到这一版',
153
+ versionsCurrent: '当前',
154
+ versionsLatest: '最新',
155
+ versionsInstalled: '已装',
156
+ versionsBlocked: '这台 DSH 装不了',
157
+ versionsDeprecated: '已废弃',
158
+ versionsNeed: '要求 DSH {r}',
159
+ versionsLoading: '读取版本…',
160
+ versionsFailed: '读不到版本列表',
161
+ versionsEmpty: '没有匹配的插件',
162
+ versionsDone: '已切到 {v}',
163
+ versionsNoop: '已经是这一版',
164
+ versionsFail: '切换失败',
165
+ versionsTotal: '共 {n} 个版本',
131
166
  maxPerCycle: '一轮最多装几个',
132
167
  maxPerCycleHint: '0 表示不限。装包会一直占着 pnpm 锁,限一个数就把单次占用封顶,剩下的下一轮接着装',
133
168
  sessionIdle: '会话静默(分钟)',
@@ -275,6 +310,41 @@ window.__ModuleLoader__.load({
275
310
  allowHint: 'one package name per line; empty means every package',
276
311
  allowMajor: 'Allow major upgrades',
277
312
  allowMajorHint: 'Off keeps upgrades inside one major; 0.x plugins would rarely move',
313
+ registry: 'Registry',
314
+ registryHint: 'Version lookups and installs both use this source. The default follows pnpm own config and changes nothing.',
315
+ regPnpm: 'Follow pnpm',
316
+ regNpmjs: 'Official',
317
+ regMirror: 'China mirror',
318
+ regCustom: 'Custom',
319
+ regUrl: 'Custom registry URL',
320
+ regUrlHint: 'http(s)://…; anything else falls back to Follow pnpm',
321
+ compatCheck: 'Check DSH compatibility first',
322
+ compatCheckHint: 'The host refuses unusable versions only after the bundle is gone; stopping earlier keeps the snapshot and the profile clean',
323
+ dshVersion: 'DSH version',
324
+ lagTitle: 'Mirror behind',
325
+ lagNote: '{n} plugin(s) not synced to the mirror yet; upstream already has newer',
326
+ blockedNote: '{n} version(s) cannot be installed on this DSH',
327
+ versionsTab: 'Versions',
328
+ versionsTitle: 'Version manager',
329
+ versionsSubtitle: 'Every published version of every installed plugin; click one to switch',
330
+ versionsSearch: 'Search plugin names',
331
+ versionsCount: '{n} plugins',
332
+ versionsShow: 'Versions',
333
+ versionsHide: 'Hide',
334
+ versionsSwitch: 'Switch to this',
335
+ versionsCurrent: 'current',
336
+ versionsLatest: 'latest',
337
+ versionsInstalled: 'installed',
338
+ versionsBlocked: 'not installable on this DSH',
339
+ versionsDeprecated: 'deprecated',
340
+ versionsNeed: 'needs DSH {r}',
341
+ versionsLoading: 'Loading versions…',
342
+ versionsFailed: 'Could not read the version list',
343
+ versionsEmpty: 'Nothing matches',
344
+ versionsDone: 'Switched to {v}',
345
+ versionsNoop: 'Already on this version',
346
+ versionsFail: 'Switch failed',
347
+ versionsTotal: '{n} versions',
278
348
  maxPerCycle: 'Installs per cycle',
279
349
  maxPerCycleHint: '0 means no limit. pnpm holds a lock for the whole install, so a cap bounds how long the profile stays busy; the rest wait for the next cycle',
280
350
  sessionIdle: 'Session quiet window (minutes)',
@@ -586,8 +656,9 @@ window.__ModuleLoader__.load({
586
656
 
587
657
  .dsh-au-input{width:96px;padding:4px 8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.32));background:var(--dsw-alias-bg-layer-2,transparent);color:inherit;font:inherit;font-size:13px;text-align:right;transition:border-color .15s}
588
658
  .dsh-au-select{padding:4px 8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.32));background:var(--dsw-alias-bg-layer-2,transparent);color:inherit;font:inherit;font-size:13px;min-width:132px;transition:border-color .15s}
659
+ .dsh-au-url{width:240px;max-width:100%;padding:4px 8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.32));background:var(--dsw-alias-bg-layer-2,transparent);color:inherit;font:inherit;font-size:12.5px;transition:border-color .15s}
589
660
  .dsh-au-search{padding:4px 8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.32));background:var(--dsw-alias-bg-layer-2,transparent);color:inherit;font:inherit;font-size:12.5px;transition:border-color .15s}
590
- .dsh-au-input:focus,.dsh-au-select:focus,.dsh-au-search:focus{outline:none;border-color:var(--dsw-alias-state-business-primary,#4d6bfe)}
661
+ .dsh-au-input:focus,.dsh-au-select:focus,.dsh-au-search:focus,.dsh-au-url:focus{outline:none;border-color:var(--dsw-alias-state-business-primary,#4d6bfe)}
591
662
  .dsh-au-input:disabled,.dsh-au-select:disabled{opacity:.55}
592
663
 
593
664
  .dsh-au-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
@@ -613,6 +684,16 @@ window.__ModuleLoader__.load({
613
684
  .dsh-au-logtime{color:var(--dsw-alias-label-caption,rgba(128,128,128,.8));font-variant-numeric:tabular-nums}
614
685
  .dsh-au-logtext{color:inherit}
615
686
 
687
+ /* 版本管理:一行版本 = 版本号 + 标记 + 右侧动作。 */
688
+ .dsh-au-vhead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}
689
+ .dsh-au-vlist{display:flex;flex-direction:column;gap:2px;max-height:300px;overflow:auto;border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.22));border-radius:10px;padding:4px;margin-top:2px}
690
+ .dsh-au-vrow{display:flex;align-items:center;gap:8px;padding:3px 6px;border-radius:6px;min-width:0}
691
+ .dsh-au-vrow:hover{background:var(--dsw-alias-bg-mask-1,rgba(128,128,128,.08))}
692
+ .dsh-au-vnum{flex:0 0 auto;min-width:92px;font-variant-numeric:tabular-nums;font-size:12.5px}
693
+ .dsh-au-vact{flex:0 0 auto;margin-left:auto}
694
+ .dsh-au-dim{color:var(--dsw-alias-label-caption,rgba(128,128,128,.85));font-size:11.5px}
695
+ .dsh-au-bad{color:var(--dsw-alias-state-error-primary,#d9534f);font-size:11.5px}
696
+ .dsh-au-pivot{flex:0 0 auto;font-size:11px;line-height:1.6;padding:0 7px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));color:var(--dsw-alias-label-secondary,inherit)}
616
697
  .dsh-au-link{color:inherit;text-decoration:none;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.4));padding-bottom:1px;transition:color .15s,border-color .15s}
617
698
  .dsh-au-link:hover{color:var(--dsw-alias-state-business-primary,#4d6bfe);border-color:currentColor}
618
699
  .dsh-au-linkext{margin-left:3px;opacity:.5}
@@ -668,6 +749,15 @@ window.__ModuleLoader__.load({
668
749
  input: 'dsh-au-input',
669
750
  select: 'dsh-au-select',
670
751
  search: 'dsh-au-search',
752
+ url: 'dsh-au-url',
753
+ vhead: 'dsh-au-vhead',
754
+ vlist: 'dsh-au-vlist',
755
+ vrow: 'dsh-au-vrow',
756
+ vnum: 'dsh-au-vnum',
757
+ vact: 'dsh-au-vact',
758
+ dim: 'dsh-au-dim',
759
+ bad: 'dsh-au-bad',
760
+ pivot: 'dsh-au-pivot',
671
761
  actions: 'dsh-au-actions',
672
762
  btn: 'dsh-au-btn',
673
763
  btnPrimary: 'dsh-au-btn dsh-au-primary',
@@ -1244,6 +1334,43 @@ window.__ModuleLoader__.load({
1244
1334
  h(SwitchRow, { label: T.allowMajor, hint: T.allowMajorHint, value: draft.allowMajor, onChange: (v) => patch('allowMajor', v) }),
1245
1335
  h(SwitchRow, { label: T.allowPrerelease, hint: T.allowPrereleaseHint, value: draft.allowPrerelease, onChange: (v) => patch('allowPrerelease', v) }),
1246
1336
  ),
1337
+ // 安装源 + 兼容性预检(0.8.0 借自 dsh-plugin-upgrader,见 docs/BORROWED-FROM-UPGRADER.md)。
1338
+ h('div', { className: S.card },
1339
+ h('h3', { className: S.h }, T.registry),
1340
+ h(SelectRow, {
1341
+ label: T.registry,
1342
+ hint: T.registryHint,
1343
+ value: draft.registryMode ?? 'pnpm',
1344
+ onChange: (v) => patch('registryMode', v),
1345
+ options: [
1346
+ { value: 'pnpm', label: T.regPnpm },
1347
+ { value: 'npmjs', label: T.regNpmjs },
1348
+ { value: 'mirror', label: T.regMirror },
1349
+ { value: 'custom', label: T.regCustom },
1350
+ ],
1351
+ }),
1352
+ (draft.registryMode ?? 'pnpm') === 'custom'
1353
+ ? h('div', { className: S.row },
1354
+ h('div', { className: S.labelBox },
1355
+ h('span', { className: S.label }, T.regUrl),
1356
+ h('span', { className: S.hint }, T.regUrlHint),
1357
+ ),
1358
+ h('input', {
1359
+ type: 'url',
1360
+ value: draft.registryUrl ?? '',
1361
+ placeholder: 'https://registry.example.com',
1362
+ onChange: (event) => patch('registryUrl', event.target.value),
1363
+ className: S.url,
1364
+ }),
1365
+ )
1366
+ : null,
1367
+ h(SwitchRow, { label: T.compatCheck, hint: T.compatCheckHint, value: draft.compatCheck !== false, onChange: (v) => patch('compatCheck', v) }),
1368
+ // 这两项是只读的现场信息:出问题时第一句话就是「你的 DSH 是哪个版本、走的哪个源」。
1369
+ h('div', { className: S.meta },
1370
+ h('span', null, T.dshVersion + ': ' + (state?.dshVersion ?? '—')),
1371
+ h('span', null, T.registry + ': ' + (state?.registry === '' || !state?.registry ? T.regPnpm : state.registry)),
1372
+ ),
1373
+ ),
1247
1374
  h('div', { className: S.card },
1248
1375
  h('h3', { className: S.h }, T.keepTitle),
1249
1376
  h('p', { className: S.note }, T.keepHint),
@@ -1339,6 +1466,16 @@ window.__ModuleLoader__.load({
1339
1466
  )),
1340
1467
  )
1341
1468
  })(),
1469
+ // 镜像落后和「装不了」都要按名字说出来:只报「已是最新」或「一个没装上」,
1470
+ // 用户没法知道该换源还是该升 DSH。
1471
+ (last?.lagged?.length ?? 0) > 0
1472
+ ? h('p', { className: S.note }, T.lagNote.replace('{n}', String(last.lagged.length)) + ' · ' +
1473
+ last.lagged.slice(0, 3).map((row) => row.name + ' ' + (row.mirror ?? '?') + ' → ' + (row.upstream ?? '?')).join(','))
1474
+ : null,
1475
+ (last?.blocked?.length ?? 0) > 0
1476
+ ? h('p', { className: S.note }, T.blockedNote.replace('{n}', String(last.blocked.length)) + ' · ' +
1477
+ last.blocked.slice(0, 3).map((row) => row.name + '@' + (row.target ?? '?')).join(','))
1478
+ : null,
1342
1479
  runHint ? h('span', { className: S.status }, runHint) : null,
1343
1480
  ),
1344
1481
  // 更新记录:谁、从哪到哪、什么时候、成没成,以及回滚入口。
@@ -1683,6 +1820,196 @@ window.__ModuleLoader__.load({
1683
1820
  }
1684
1821
  }
1685
1822
 
1823
+ /**
1824
+ * 「版本管理」标签页。
1825
+ *
1826
+ * 和设置页的分工:设置页管「什么时候自动升」,这一页管「现在就要某一版」。
1827
+ * 版本列表按包按需拉(一次一个包),不进首屏:整页一次拉一堆包的 packument
1828
+ * 在镜像上会慢到没法用。
1829
+ */
1830
+ function VersionsTab() {
1831
+ useLang()
1832
+ const [state, setState] = useState(null)
1833
+ const [query, setQuery] = useState('')
1834
+ const [openName, setOpenName] = useState('')
1835
+ const [lists, setLists] = useState({})
1836
+ const [loadError, setLoadError] = useState('')
1837
+ const [busy, setBusy] = useState('')
1838
+ const [hint, setHint] = useState('')
1839
+
1840
+ const reload = useCallback(async () => {
1841
+ try {
1842
+ setState(await getState(LANG))
1843
+ } catch {}
1844
+ }, [])
1845
+
1846
+ useEffect(() => { void reload() }, [reload])
1847
+
1848
+ // 切版本可能要好几分钟(pnpm 要校验锁文件),期间才轮询;闲着时一个请求都不发。
1849
+ useEffect(() => {
1850
+ if (busy === '') return undefined
1851
+ const timer = setInterval(async () => {
1852
+ try {
1853
+ setState(await getState(LANG))
1854
+ } catch {}
1855
+ }, 3000)
1856
+ return () => clearInterval(timer)
1857
+ }, [busy])
1858
+
1859
+ const openVersions = useCallback(async (name) => {
1860
+ if (openName === name) {
1861
+ setOpenName('')
1862
+ return
1863
+ }
1864
+ setOpenName(name)
1865
+ setLoadError('')
1866
+ if (lists[name] !== undefined) return
1867
+ try {
1868
+ const response = await fetch(endpoint('versions') + '?name=' + encodeURIComponent(name) + '&lang=' + (LANG === 'en' ? 'en' : 'zh'), {
1869
+ headers: { accept: 'application/json' },
1870
+ cache: 'no-store',
1871
+ })
1872
+ if (!response.ok) throw new Error('versions ' + response.status)
1873
+ const payload = await response.json()
1874
+ setLists((prev) => ({ ...prev, [name]: payload }))
1875
+ } catch {
1876
+ setLoadError(T.versionsFailed)
1877
+ }
1878
+ }, [openName, lists])
1879
+
1880
+ const doSwitch = useCallback(async (name, version) => {
1881
+ if (busy !== '') return
1882
+ setBusy(name + '@' + version)
1883
+ setHint('')
1884
+ try {
1885
+ const response = await fetch(endpoint('switch') + langQuery(), {
1886
+ method: 'POST',
1887
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
1888
+ body: JSON.stringify({ name, version }),
1889
+ })
1890
+ const payload = await response.json().catch(() => null)
1891
+ if (response.ok) {
1892
+ setHint(payload?.unchanged === true ? T.versionsNoop : T.versionsDone.replace('{v}', version))
1893
+ // 版本变了,这个包的缓存列表要作废,否则「当前」标记还停在旧版本上。
1894
+ setLists((prev) => {
1895
+ const next = { ...prev }
1896
+ delete next[name]
1897
+ return next
1898
+ })
1899
+ await reload()
1900
+ } else {
1901
+ setHint(T.versionsFail + ' · ' + (payload?.reason || payload?.detail || ('HTTP ' + response.status)))
1902
+ }
1903
+ } catch {
1904
+ setHint(T.versionsFail)
1905
+ } finally {
1906
+ setBusy('')
1907
+ }
1908
+ }, [busy, reload])
1909
+
1910
+ const packages = useMemo(() => {
1911
+ const all = Array.isArray(state?.packages) ? state.packages : []
1912
+ const text = query.trim().toLowerCase()
1913
+ return text === '' ? all : all.filter((item) => String(item.name).toLowerCase().includes(text))
1914
+ }, [state, query])
1915
+
1916
+ const progress = state?.progress
1917
+ const runningText = (() => {
1918
+ if (!progress) return ''
1919
+ if (progress.phase === 'installing' && progress.total > 0) {
1920
+ return T.progressInstall
1921
+ .replace('{n}', String(progress.index))
1922
+ .replace('{m}', String(progress.total))
1923
+ .replace('{name}', String(progress.name || ''))
1924
+ }
1925
+ if (progress.phase === 'applying') return T.progressApply
1926
+ return T.running
1927
+ })()
1928
+
1929
+ return h('div', { className: S.wrap },
1930
+ h('div', { className: S.head },
1931
+ h('h3', { className: S.title }, T.versionsTitle),
1932
+ h('p', { className: S.sub }, T.versionsSubtitle),
1933
+ ),
1934
+ h('div', { className: S.card },
1935
+ h('div', { className: S.vhead },
1936
+ h('input', {
1937
+ type: 'search',
1938
+ value: query,
1939
+ placeholder: T.versionsSearch,
1940
+ onChange: (event) => setQuery(event.target.value),
1941
+ className: S.search,
1942
+ style: { flex: '1 1 200px' },
1943
+ }),
1944
+ h('span', { className: S.hint }, T.versionsCount.replace('{n}', String(packages.length))),
1945
+ ),
1946
+ h('div', { className: S.meta },
1947
+ h('span', null, T.dshVersion + ': ' + (state?.dshVersion ?? '—')),
1948
+ h('span', null, T.registry + ': ' + (state?.registry === '' || !state?.registry ? T.regPnpm : state.registry)),
1949
+ ),
1950
+ progress ? h('span', { className: 'dsh-au-badge run' }, runningText) : null,
1951
+ hint ? h('span', { className: S.status }, hint) : null,
1952
+ loadError ? h('p', { className: S.err }, loadError) : null,
1953
+ packages.length === 0
1954
+ ? h('span', { className: S.status }, T.versionsEmpty)
1955
+ : h('div', { className: S.scrollList },
1956
+ packages.map((item) => {
1957
+ const listed = lists[item.name]
1958
+ const expanded = openName === item.name
1959
+ return h('div', { key: item.name, style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
1960
+ h('div', { className: S.row },
1961
+ h('div', { className: S.labelBox },
1962
+ h('span', { title: item.name }, item.name),
1963
+ h('span', { className: S.hint },
1964
+ T.versionsInstalled + ' ' + (item.version === '' ? '—' : item.version) +
1965
+ (listed && listed.tagVersion !== '' ? ' · ' + T.versionsLatest + ' ' + listed.tagVersion : '')),
1966
+ ),
1967
+ h('button', {
1968
+ type: 'button',
1969
+ className: expanded ? S.btn : S.btn,
1970
+ onClick: () => void openVersions(item.name),
1971
+ }, expanded ? T.versionsHide : T.versionsShow),
1972
+ ),
1973
+ expanded
1974
+ ? listed === undefined
1975
+ ? h('span', { className: S.hint }, T.versionsLoading)
1976
+ : h('div', { className: S.vlist },
1977
+ h('span', { className: S.dim }, T.versionsTotal.replace('{n}', String(listed.total ?? 0)) +
1978
+ (listed.latest !== '' ? ' · ' + T.versionsLatest + ' ' + listed.latest : '')),
1979
+ (listed.versions ?? []).map((row) => {
1980
+ const isCurrent = row.version === item.version
1981
+ const blocked = row.ok === false
1982
+ return h('div', { key: row.version, className: S.vrow },
1983
+ h('span', { className: S.vnum }, row.version),
1984
+ isCurrent ? h('span', { className: S.pivot }, T.versionsCurrent) : null,
1985
+ row.version === listed.latest && !isCurrent ? h('span', { className: S.pivot }, T.versionsLatest) : null,
1986
+ row.deprecated === true ? h('span', { className: S.dim }, T.versionsDeprecated) : null,
1987
+ blocked
1988
+ ? h('span', { className: S.bad, title: T.versionsNeed.replace('{r}', row.need || '?') }, T.versionsBlocked)
1989
+ : null,
1990
+ h('div', { className: S.vact },
1991
+ isCurrent
1992
+ ? null
1993
+ : h('button', {
1994
+ type: 'button',
1995
+ className: blocked ? S.btn : S.btnPrimary,
1996
+ disabled: blocked || busy !== '',
1997
+ title: blocked ? T.versionsNeed.replace('{r}', row.need || '?') : '',
1998
+ onClick: () => void doSwitch(item.name, row.version),
1999
+ }, busy === item.name + '@' + row.version ? T.running : T.versionsSwitch),
2000
+ ),
2001
+ )
2002
+ }),
2003
+ )
2004
+ : null,
2005
+ )
2006
+ }),
2007
+ ),
2008
+ ),
2009
+ h('span', { className: S.hint }, T.scope),
2010
+ )
2011
+ }
2012
+
1686
2013
  return {
1687
2014
  inject: ['slots'],
1688
2015
  apply(ctx) {
@@ -1711,6 +2038,15 @@ window.__ModuleLoader__.load({
1711
2038
  order: 36,
1712
2039
  label: () => T.pageLabel,
1713
2040
  }, () => h(AutoUpdateCard)))
2041
+
2042
+ // 插件页标签栏多一个「版本管理」:和设置页分工——设置页管「什么时候自动升」,
2043
+ // 这一页管「现在就要某一版」。order 2 排在「已安装/发现」(0) 和市场(1) 之后。
2044
+ ctx.slots.inject('plugins.tab', () => ctx.slots.register({
2045
+ name: 'plugins.tab',
2046
+ id: NS,
2047
+ order: 2,
2048
+ label: () => T.versionsTab,
2049
+ }, () => h(VersionsTab)))
1714
2050
  },
1715
2051
  }
1716
2052
  },
@@ -0,0 +1,36 @@
1
+ # 从 dsh-plugin-upgrader 学什么(差距清单)
2
+
3
+ 对照对象:[zuwenyin/dsh-plugin-upgrader](https://github.com/zuwenyin/dsh-plugin-upgrader) 1.10.0(MIT,npm 上有 provenance 证明)。
4
+ 它和 dsh-aupdate 是同类:都在插件页补「一键升级」。区别是它手动触发、把精力放在**版本可见性和安装前后的边界**上,
5
+ aupdate 自动跑、把精力放在**调度和让开**上。
6
+
7
+ 这份清单是 0.7.5 的施工依据:只有能落在 aupdate 现有架构里的项才做,做了的写明代价,没做的写明为什么。
8
+
9
+ ## 可借鉴项
10
+
11
+ | 能力 | 它怎么做 | aupdate 0.7.5 | 代价 / 边界 |
12
+ | --- | --- | --- | --- |
13
+ | **按版本比 DSH 兼容性** | 装之前先查该版本 manifest 的 `engines.dsh`(没有才看 `@deepseek-ai/dsh(-*)` 的 peer),和宿主版本比 | ✅ 已实现(`compatOf`),不满足的版本不进安装队列 | 每个**候选**版本多一次几 KB 的 manifest 请求;只在「已经决定要升」时发生,不是每包每轮 |
14
+ | **DSH 版本从哪来** | 从 `process.argv` 的入口往上找 `@deepseek-ai/dsh-app-boot/package.json` | ✅ 已实现(`dshVersion`) | 读不到就返回 null 并**不拦**:宁可漏拦,也不按猜的版本误拦 |
15
+ | **安装源切换** | 顶部「注册表」对话框:自带源 / pluginManager 源 / 自建源,可测速 | ✅ 已实现(`registryMode` + `registryUrl`),三种预设 + 自定义 | 只用 `npm_config_registry` 传给子进程,**不写** `.npmrc`、不改 pnpm 配置;没选源时一个字节都不动 |
16
+ | **镜像落后单独标出** | 官方源已发布、镜像没同步时单独标一行 | ✅ 已实现(`mirrorLagOf`),写进 `lastRun.lagged`,界面按名字列出 | 只有用镜像时对每个包多一次官方源 dist-tags 请求;用官方源时零额外请求 |
17
+ | **重启指引** | 读宿主 pid 与启动方式,给出能完成重启的那一条命令 | ❌ 没做 | aupdate 的默认路径是热生效(hmr),需要重启时已经有「重启后生效」这句;再做一套 pid 追踪属于另一个功能面 |
18
+ | **插件页「版本」标签** | 顶栏多一个标签,展开插件看全部已发布版本,点一下切过去 | ✅ 已实现「版本管理」标签页(`plugins.tab`),复用同一条安装/预检/历史路径 | 按包按需拉缩略 packument;一次一个包,不进首屏 |
19
+ | **多选卸载** | 走宿主 `removeBundle`,先列清单再确认 | ❌ 没做 | 卸载是不可逆动作,和 aupdate「只负责升」的边界冲突;dsh 自带已安装页已经能卸 |
20
+ | **收紧 pnpm 重试等待** | 往 `pnpm-workspace.yaml` 追加 `fetchTimeout/fetchRetries/...` | ❌ 没做 | 它会改 profile 的共享配置文件,影响该 profile 里**所有** pnpm;这种横切改动该由用户决定,不该由自动更新插件在后台悄悄做 |
21
+ | **「需处理」可归零计数** | 只数用户能自己修的问题 | ⚠️ 部分:`lagged` / `blocked` 单独列 | 完整版的四项里,「构建待批准」aupdate 根本没有这条路径 |
22
+ | **一键复制诊断** | 纯客户端把版本、源、每行问题拼成 markdown | ❌ 没做 | 低价值;`/state` 已经把 `dshVersion`、`registry`、`lagged`、`blocked` 都吐出来了 |
23
+ | **按版本列表回滚** | 展开插件看全部已发布版本 | ❌ 没做 | 要读整份 packument(最大单包 26 MB);aupdate 滚回的是**自己装过**的版本,记录在本地,不需要联网 |
24
+
25
+ ## 刻意不照搬的
26
+
27
+ - **整份 packument 换版本列表**:它为了版本历史和兼容性标记读 packument,aupdate 一直只用 `dist-tags` 那个几百字节的端点(24 个包 2.88 MB → 655 B)。按包按需读单个版本 manifest 是更便宜的等价做法。
28
+ - **in-place 替换(先摘 manifest 再装)**:它靠临时改 profile 的 `package.json` 做到「不卸载换版本」,配了 journal 和写入锁。aupdate 走 `dsh plugin add pkg@version`,这条命令本身就会换版本;再自己动 manifest 等于和 plugin-manager 抢同一份文件,风险大于收益。
29
+ - **自动写 pnpm 配置**:见上表。
30
+
31
+ ## 0.7.5 的验收点
32
+
33
+ 1. 没选安装源时:`/state.registry === ''`,dist-tags 仍走官方源,安装命令环境变量不变。
34
+ 2. 选镜像时:`lastRun.lagged` 能列出「镜像 x.y.z、官方 a.b.c」。
35
+ 3. 目标版本要求 `DSH >=0.3.0` 而宿主是 0.2.x:该版本不进 `updates`,`lastRun.blocked` 有它,日志一行 `compatBlocked`。
36
+ 4. 服务器读不到 DSH 版本:`/state.dshVersion === null`,兼容性预检不拦任何包(回到改造前行为)。
package/index.js CHANGED
@@ -234,6 +234,22 @@ function makeLogTemplates(lang) {
234
234
  ? `清理${kind}:删掉 ${rows} 条超过 ${days} 天的`
235
235
  : `Cleaned ${kind}: removed ${rows} entr${rows === 1 ? 'y' : 'ies'} older than ${days} day(s)`),
236
236
  cleanSkipped: (kind) => (zh ? `${kind}没有需要清理的` : `Nothing to clean in ${kind}`),
237
+ compatBlocked: (name, version, range, dsh) => (zh
238
+ ? `${name}@${version} 跳过:要求 DSH ${range},当前 ${dsh}`
239
+ : `${name}@${version} skipped: needs DSH ${range}, host is ${dsh}`),
240
+ mirrorLag: (name, upstream, mirror) => (zh
241
+ ? `${name} 镜像落后:镜像 ${mirror},官方 ${upstream}`
242
+ : `${name} mirror lag: mirror ${mirror}, upstream ${upstream}`),
243
+ registryPicked: (source) => (zh ? `安装源:${source}` : `Registry: ${source}`),
244
+ switching: (name, from, to) => (zh
245
+ ? '切换版本:' + name + ' ' + from + ' → ' + to
246
+ : 'Switching: ' + name + ' ' + from + ' → ' + to),
247
+ switched: (name, from, to) => (zh
248
+ ? '已切换:' + name + ' ' + from + ' → ' + to
249
+ : 'Switched: ' + name + ' ' + from + ' → ' + to),
250
+ reloaded: (status, reason) => (zh
251
+ ? '就地生效:' + status + (reason ? '(' + reason + ')' : '')
252
+ : 'Apply in place: ' + status + (reason ? ' (' + reason + ')' : '')),
237
253
  ready: (minutes, autoApply, hotReload) => (zh
238
254
  ? `已就绪:每 ${minutes} 分钟检查一次,自动安装=${onOff(autoApply)},就地生效=${onOff(hotReload)}`
239
255
  : `Ready: every ${minutes} min, autoApply=${onOff(autoApply)}, hotReload=${onOff(hotReload)}`),
@@ -269,6 +285,15 @@ function makeReasonTemplates(lang) {
269
285
  noInstalled: () => (zh ? '读不到已装版本' : 'Installed version unreadable'),
270
286
  suppressed: (stamp) => (zh ? `上次安装失败,${stamp} UTC 前不再重试` : `Install failed before; not retried until ${stamp} UTC`),
271
287
  lookupFailed: (msg) => (zh ? `查不到:${msg}` : `Lookup failed: ${msg}`),
288
+ compatBlocked: (version, range, dsh) => (zh
289
+ ? `${version} 要求 DSH ${range},当前宿主是 ${dsh},没装`
290
+ : `${version} needs DSH ${range}; this host is ${dsh}, not installed`),
291
+ incompatible: (range, dsh) => (zh
292
+ ? `已装的版本要求 DSH ${range},当前宿主是 ${dsh}`
293
+ : `The installed version needs DSH ${range}; this host is ${dsh}`),
294
+ mirrorLag: (upstream, mirror) => (zh
295
+ ? `镜像还停在 ${mirror},官方源已经是 ${upstream}`
296
+ : `The mirror still has ${mirror}; upstream is at ${upstream}`),
272
297
  agentsBusy: (n) => (zh ? `${n} 个子任务在跑` : `${n} subagent(s) running`),
273
298
  sessionActive: (age) => (zh ? `会话在 ${ageText(age)} 分钟前还在写入` : `Session was written ${ageText(age)} min ago`),
274
299
  noDeps: () => (zh ? '这个 profile 里没有可检查的依赖' : 'No dependencies to check in this profile'),
@@ -514,6 +539,8 @@ const OVERRIDEABLE = [
514
539
  'enabled', 'autoApply', 'hotReload', 'checkOnStart', 'idleOnly', 'notify',
515
540
  'intervalMinutes', 'firstDelayMinutes', 'exclude',
516
541
  'allowMajor', 'allowPrerelease',
542
+ // 安装源与兼容性预检(0.8.0 借自 dsh-plugin-upgrader)。
543
+ 'registryMode', 'registryUrl', 'compatCheck',
517
544
  // 调度:四种节奏 + 失败抑制时长。这些键不写进 Config schema,
518
545
  // 只活在覆盖层里——Config 的字段类型是宿主校验的,加错一个类型
519
546
  // 会在加载期直接抛错,而覆盖层是我们自己的文件,改坏了只影响这一项。
@@ -706,6 +733,13 @@ function settingsOf(config) {
706
733
  // 发现可更新版本时是否弹出提醒。默认开着:定时更新最容易出的事,是它一直在
707
734
  // 后台装,用户根本不知道装了什么、装到哪一版。
708
735
  notify: booleanSetting(config, 'notify', true),
736
+ // 安装源:默认跟随 pnpm,选别的才动(生效值见 registryOf)。
737
+ registryMode: registryModeOf(config),
738
+ registryUrl: typeof config?.registryUrl === 'string' ? config.registryUrl : '',
739
+ registry: registryOf(config),
740
+ // 兼容性预检:装之前先看目标版本声明的 DSH 范围。默认开——宿主闸门是在
741
+ // bundle 已经卸下之后才拒绝的,等它拒绝就已经晚了。
742
+ compatCheck: booleanSetting(config, 'compatCheck', true),
709
743
  intervalMinutes: numberSetting(config, 'intervalMinutes', 1440, 10, 10080),
710
744
  firstDelayMinutes: numberSetting(config, 'firstDelayMinutes', 5, 0, 1440),
711
745
  exclude: stringList(config?.exclude),
@@ -863,6 +897,13 @@ function readLastRun() {
863
897
  ? raw.reason
864
898
  : (raw.reason !== null && typeof raw.reason === 'object' ? raw.reason : ''),
865
899
  snapshot: typeof raw.snapshot === 'string' ? raw.snapshot : '',
900
+ // 0.7.x 及更早没有这两项;缺了就是空数组,不当成坏数据。
901
+ lagged: Array.isArray(raw.lagged)
902
+ ? raw.lagged.filter((row) => row !== null && typeof row === 'object' && typeof row.name === 'string')
903
+ : [],
904
+ blocked: Array.isArray(raw.blocked)
905
+ ? raw.blocked.filter((row) => row !== null && typeof row === 'object' && typeof row.name === 'string')
906
+ : [],
866
907
  }
867
908
  }
868
909
 
@@ -1090,6 +1131,343 @@ function compareVersions(a, b) {
1090
1131
  function distTagFor(pkgName) {
1091
1132
  return NEXT_TAG_SCOPES.some((prefix) => pkgName.startsWith(prefix)) ? 'next' : 'latest'
1092
1133
  }
1134
+
1135
+ /* ── 安装源 / 兼容性预检 / 镜像落后 ─────────────────────────────────────
1136
+ *
1137
+ * 这三样是从 dsh-plugin-upgrader 学来的(差距清单见 docs/BORROWED-FROM-UPGRADER.md),
1138
+ * 但按 aupdate 自己的量级实现:
1139
+ *
1140
+ * - 安装源:没选就不干预——dist-tags 走官方源、pnpm 用自己配置的源,和改造前
1141
+ * 一个字节都不差;选了才把 dist-tags 和 npm_config_registry 一起换过去。
1142
+ * - 兼容性预检:只在「已经决定要装这个版本」时读一次该版本的 manifest(几 KB),
1143
+ * 不像竞品那样为了版本列表去拉整份 packument(24 个包 2.88 MB)。
1144
+ * - 镜像落后:只有用了镜像才多查一次官方源的 dist-tags,默认零额外请求。
1145
+ */
1146
+ const OFFICIAL_REGISTRY = 'https://registry.npmjs.org'
1147
+ const REGISTRY_MIRROR = 'https://registry.npmmirror.com'
1148
+ const REGISTRY_MODES = ['pnpm', 'npmjs', 'mirror', 'custom']
1149
+
1150
+ function registryModeOf(config) {
1151
+ const mode = typeof config?.registryMode === 'string' ? config.registryMode : ''
1152
+ return REGISTRY_MODES.includes(mode) ? mode : 'pnpm'
1153
+ }
1154
+
1155
+ /**
1156
+ * 生效的源;'' 表示不干预。
1157
+ *
1158
+ * 自定义源只认 http(s) 并去掉尾部斜杠:后头是直接拼 URL 的,不校验的话一个
1159
+ * file: 或者带空格的串会变成更难查的「查不到版本」。
1160
+ */
1161
+ function registryOf(config) {
1162
+ const mode = registryModeOf(config)
1163
+ if (mode === 'pnpm') return ''
1164
+ if (mode === 'npmjs') return OFFICIAL_REGISTRY
1165
+ if (mode === 'mirror') return REGISTRY_MIRROR
1166
+ const raw = typeof config?.registryUrl === 'string' ? config.registryUrl.trim().replace(/\/+$/u, '') : ''
1167
+ return /^https?:\/\/[^\s]+$/iu.test(raw) ? raw : ''
1168
+ }
1169
+
1170
+ /** 查 dist-tags 用的基地址:没选源也走官方源(和改造前一致)。 */
1171
+ function tagsBaseOf(registry) {
1172
+ return registry === '' ? OFFICIAL_REGISTRY : registry
1173
+ }
1174
+
1175
+ /**
1176
+ * 当前宿主真正在跑的 DSH 版本。
1177
+ *
1178
+ * 兼容性闸门比的是 @deepseek-ai/dsh-app-boot 的版本——入口加载的是哪一份,闸门
1179
+ * 就用哪一份。桌面版入口在 app.asar 里,命令行启动看到的是 profile 里那份,两者
1180
+ * 可能不是同一个构建;从入口往上找是两种布局都对读法,读一个写死的路径会在两者
1181
+ * 不一致时骗人。读不到就返回 null:宁可漏拦,也不要按猜的版本误拦。
1182
+ */
1183
+ let dshVersionMemo = null
1184
+ const RUNTIME_PACKAGE = '@deepseek-ai/dsh-app-boot'
1185
+
1186
+ function dshVersion() {
1187
+ if (dshVersionMemo !== null) return dshVersionMemo
1188
+ const versionAt = (file) => {
1189
+ const raw = readJson(file)
1190
+ return raw !== null && typeof raw.version === 'string' && raw.version.trim() !== '' ? raw.version.trim() : null
1191
+ }
1192
+ const beside = (entry) => {
1193
+ let dir = dirname(entry)
1194
+ for (let depth = 0; depth < 10; depth += 1) {
1195
+ const found = versionAt(join(dir, 'node_modules', RUNTIME_PACKAGE, 'package.json'))
1196
+ if (found !== null) return found
1197
+ const up = dirname(dir)
1198
+ if (up === dir) return null
1199
+ dir = up
1200
+ }
1201
+ return null
1202
+ }
1203
+ try {
1204
+ for (const entry of process.argv.slice(1, 7)) {
1205
+ if (typeof entry !== 'string' || !/[.]c?js$/iu.test(entry)) continue
1206
+ const found = beside(entry)
1207
+ if (found !== null) {
1208
+ dshVersionMemo = found
1209
+ return found
1210
+ }
1211
+ }
1212
+ } catch {}
1213
+ return null
1214
+ }
1215
+
1216
+ /**
1217
+ * 一个 range 是否接受这个版本。
1218
+ *
1219
+ * 只实现真正会遇到的那几种写法(比较符组合、^、~、裸版本号、x/星号)。遇到
1220
+ * 看不懂的(||、连字符区间、nested)一律放行:这套逻辑的用途是「提前拦住装不上
1221
+ * 的版本」,漏拦只是回到改造前的行为,误拦却会让一个本来能升的包永远不升。
1222
+ */
1223
+ function satisfiesRange(range, version) {
1224
+ const text = String(range ?? '').trim()
1225
+ if (text === '') return true
1226
+ if (parseVersion(version) === null) return true
1227
+ if (text.includes('||')) return true
1228
+ const parts = text.split(/\s+/u).filter(Boolean)
1229
+ if (parts.length === 0) return true
1230
+ for (const part of parts) if (!satisfiesOne(part, version)) return false
1231
+ return true
1232
+ }
1233
+
1234
+ function satisfiesOne(part, version) {
1235
+ const match = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/u.exec(part)
1236
+ if (match === null) return true
1237
+ const op = match[1] ?? ''
1238
+ const wantedRaw = match[2].trim()
1239
+ const wanted = parseVersion(wantedRaw)
1240
+ const got = parseVersion(version)
1241
+ if (got === null) return true
1242
+ // 1.x / 1.2.x / * 这类认不出完整版本号的,当通配处理。
1243
+ if (wanted === null) return true
1244
+ const cmp = compareVersions(version, wantedRaw)
1245
+ if (cmp === null) return true
1246
+ const [gotMajor, gotMinor] = got.core
1247
+ const [wantMajor, wantMinor] = wanted.core
1248
+ switch (op) {
1249
+ case '>=': return cmp >= 0
1250
+ case '>': return cmp > 0
1251
+ case '<=': return cmp <= 0
1252
+ case '<': return cmp < 0
1253
+ case '=': return cmp === 0
1254
+ case '^':
1255
+ // ^0.2.1 → >=0.2.1 <0.3.0;^1.2.3 → >=1.2.3 <2.0.0
1256
+ if (cmp < 0) return false
1257
+ if (wantMajor > 0) return gotMajor === wantMajor
1258
+ if (wantMinor > 0) return gotMajor === 0 && gotMinor === wantMinor
1259
+ return gotMajor === 0 && gotMinor === 0 && wanted.core[2] === got.core[2]
1260
+ case '~': return cmp >= 0 && gotMajor === wantMajor && gotMinor === wantMinor
1261
+ default: {
1262
+ const segments = wantedRaw.split('.').length
1263
+ if (segments >= 3) return cmp === 0
1264
+ if (segments === 2) return gotMajor === wantMajor && gotMinor === wantMinor
1265
+ return gotMajor === wantMajor
1266
+ }
1267
+ }
1268
+ }
1269
+
1270
+ /**
1271
+ * 一个已发布版本声明的 DSH 要求。
1272
+ *
1273
+ * 顺序照宿主闸门:有 engines.dsh 就只认它,没有才看 @deepseek-ai/dsh(-*) 的 peer。
1274
+ * 反过来读会把宿主随后会拒绝的版本标成可用,正是这条路径要防的事。
1275
+ */
1276
+ const DSH_PEER = '@deepseek-ai/dsh'
1277
+ const DSH_PEER_PREFIX = '@deepseek-ai/dsh-'
1278
+
1279
+ function dshRequirementOf(manifest) {
1280
+ if (manifest === null || typeof manifest !== 'object') return null
1281
+ const engines = manifest.engines
1282
+ if (engines !== null && typeof engines === 'object' && typeof engines.dsh === 'string' && engines.dsh.trim() !== '') {
1283
+ return { range: engines.dsh.trim().replace(/^workspace:/u, ''), from: 'engines.dsh' }
1284
+ }
1285
+ const peers = manifest.peerDependencies
1286
+ if (peers === null || typeof peers !== 'object') return null
1287
+ const rank = (key) => (key === DSH_PEER ? 0 : key.startsWith(DSH_PEER_PREFIX) ? 1 : 2)
1288
+ const entries = Object.entries(peers)
1289
+ .filter(([key, value]) => rank(key) < 2 && typeof value === 'string' && value !== '' && !value.startsWith('workspace:'))
1290
+ .sort((a, b) => rank(a[0]) - rank(b[0]))
1291
+ if (entries.length === 0) return null
1292
+ return { range: entries[0][1].trim(), from: 'peer ' + entries[0][0] }
1293
+ }
1294
+
1295
+ const manifestCache = new Map()
1296
+
1297
+ /** 单个已发布版本的 manifest(几 KB),带缓存。 */
1298
+ async function versionManifestOf(pkgName, version, registry) {
1299
+ const key = tagsBaseOf(registry) + '|' + pkgName + '|' + version
1300
+ const hit = manifestCache.get(key)
1301
+ if (hit !== undefined && Date.now() - hit.at < TAG_TTL_MS) return hit.value
1302
+ const url = tagsBaseOf(registry) + '/' + pkgName.replace('/', '%2f') + '/' + encodeURIComponent(version)
1303
+ const response = await fetch(url, {
1304
+ headers: { accept: 'application/json' },
1305
+ signal: AbortSignal.timeout(8000),
1306
+ })
1307
+ if (!response.ok) throw new Error('registry ' + response.status)
1308
+ const value = await response.json()
1309
+ manifestCache.set(key, { at: Date.now(), value })
1310
+ if (manifestCache.size > 200) {
1311
+ const oldest = manifestCache.keys().next()
1312
+ if (!oldest.done) manifestCache.delete(oldest.value)
1313
+ }
1314
+ return value
1315
+ }
1316
+
1317
+ /**
1318
+ * 这个版本能不能装在这台宿主上。
1319
+ *
1320
+ * 返回 null 表示「说不了」:DSH 版本读不到、manifest 查不到、这个包根本没声明
1321
+ * 要求——三种情况都不拦,照常装。只有明确不满足时才返回 ok:false。
1322
+ */
1323
+ async function compatOf(pkgName, version, registry) {
1324
+ const dsh = dshVersion()
1325
+ if (dsh === null) return null
1326
+ let manifest
1327
+ try {
1328
+ manifest = await versionManifestOf(pkgName, version, registry)
1329
+ } catch {
1330
+ return null
1331
+ }
1332
+ const need = dshRequirementOf(manifest)
1333
+ if (need === null) return null
1334
+ return { ok: satisfiesRange(need.range, dsh), range: need.range, from: need.from, dsh }
1335
+ }
1336
+
1337
+ /**
1338
+ * 镜像落后:官方源已经有更新的版本,你在用的镜像还没同步。
1339
+ *
1340
+ * 只比 dist-tags 上那一个标签。镜像模式下每个包多一次很小的请求;不选镜像时
1341
+ * 直接返回 null,一个请求都不发。
1342
+ */
1343
+ async function mirrorLagOf(pkgName, registry, mirrorTags) {
1344
+ if (registry === '' || tagsBaseOf(registry) === OFFICIAL_REGISTRY) return null
1345
+ try {
1346
+ const upstream = await registryTags(pkgName, OFFICIAL_REGISTRY)
1347
+ const tag = distTagFor(pkgName)
1348
+ const up = typeof upstream[tag] === 'string' ? upstream[tag] : null
1349
+ const mirror = typeof mirrorTags?.[tag] === 'string' ? mirrorTags[tag] : null
1350
+ if (up === null || mirror === null) return null
1351
+ const cmp = compareVersions(up, mirror)
1352
+ return cmp !== null && cmp > 0 ? { tag, upstream: up, mirror } : null
1353
+ } catch {
1354
+ return null
1355
+ }
1356
+ }
1357
+
1358
+ /* ── 版本管理 ───────────────────────────────────────────────────────────
1359
+ *
1360
+ * 「插件」页多一个标签页,列每个已装插件的全部已发布版本,可以点到某一版。
1361
+ *
1362
+ * 只读缩略 packument(Accept: application/vnd.npm.install-v1+json):它保留
1363
+ * versions 里每个版本的 engines/deprecated,正好是这里要判断的东西,而把
1364
+ * readme、tarball 元数据和 maintainer 全砍掉了。整份 packument 最大单包 26 MB,
1365
+ * 缩略版 10 MB,常见插件只有几 KB —— 这个差别决定了能不能一页列一排包的版本。
1366
+ */
1367
+ const MAX_VERSIONS = 80
1368
+ const versionsCache = new Map()
1369
+ const VERSIONS_TTL_MS = 5 * 60 * 1000
1370
+ const ABBREVIATED_ACCEPT = 'application/vnd.npm.install-v1+json'
1371
+
1372
+ async function publishedVersions(pkgName, registry) {
1373
+ const base = tagsBaseOf(registry)
1374
+ const key = base + '|' + pkgName
1375
+ const hit = versionsCache.get(key)
1376
+ if (hit !== undefined && Date.now() - hit.at < VERSIONS_TTL_MS) return hit.value
1377
+ const url = base + '/' + pkgName.replace('/', '%2f')
1378
+ const response = await fetch(url, {
1379
+ headers: { accept: ABBREVIATED_ACCEPT },
1380
+ // 慢的包(几千个版本那种)在镜像上要几秒;超时就回报失败,不拖住整页。
1381
+ signal: AbortSignal.timeout(15000),
1382
+ })
1383
+ if (!response.ok) throw new Error('registry ' + response.status)
1384
+ const doc = await response.json()
1385
+ const packs = doc?.versions !== null && typeof doc?.versions === 'object' ? doc.versions : {}
1386
+ const tags = doc?.['dist-tags'] !== null && typeof doc?.['dist-tags'] === 'object' ? doc['dist-tags'] : {}
1387
+ const dsh = dshVersion()
1388
+ const rows = []
1389
+ for (const [version, manifest] of Object.entries(packs)) {
1390
+ if (parseVersion(version) === null) continue
1391
+ const need = dshRequirementOf(manifest)
1392
+ rows.push({
1393
+ version,
1394
+ // 宿主闸门读的是同一个字段,这里算出来的结论和它一致。
1395
+ need: need === null ? '' : need.range,
1396
+ ok: need === null || dsh === null ? null : satisfiesRange(need.range, dsh),
1397
+ deprecated: typeof manifest?.deprecated === 'string' && manifest.deprecated !== '',
1398
+ })
1399
+ }
1400
+ rows.sort((a, b) => (compareVersions(b.version, a.version) ?? 0))
1401
+ const tag = distTagFor(pkgName)
1402
+ const value = {
1403
+ name: pkgName,
1404
+ latest: typeof tags.latest === 'string' ? tags.latest : '',
1405
+ tag,
1406
+ tagVersion: typeof tags[tag] === 'string' ? tags[tag] : '',
1407
+ total: rows.length,
1408
+ versions: rows.slice(0, MAX_VERSIONS),
1409
+ }
1410
+ versionsCache.set(key, { at: Date.now(), value })
1411
+ if (versionsCache.size > 60) {
1412
+ const oldest = versionsCache.keys().next()
1413
+ if (!oldest.done) versionsCache.delete(oldest.value)
1414
+ }
1415
+ return value
1416
+ }
1417
+
1418
+ /** 正在切版本时挡住定时轮次,反过来也一样:pnpm 是按 profile 上一把锁的。 */
1419
+ let switching = null
1420
+
1421
+ /**
1422
+ * 把某个插件切到指定版本。
1423
+ *
1424
+ * 和整轮更新走同一条安装路径(installOne → 回读磁盘版本 → 记历史),只是不带
1425
+ * 调度、抑制和单轮上限。兼容性预检在这里同样生效:宿主的闸门要等 bundle 卸下
1426
+ * 之后才拒绝,切到装不上的版本会留下一个半装的样子。
1427
+ */
1428
+ async function switchVersion(ctxRef, pkgName, version) {
1429
+ if (switching !== null || running !== null) return { ok: false, reason: { code: 'runBusy' } }
1430
+ const settings = settingsOf(ctxRef.config)
1431
+ const profileDir = profileDirOf(ctxRef.ctx)
1432
+ const profileName = basename(profileDir)
1433
+ const current = installedVersion(profileDir, pkgName, null)
1434
+ if (current === version) return { ok: true, unchanged: true, from: current, to: version, detail: '' }
1435
+ const compat = await compatOf(pkgName, version, settings.registry)
1436
+ if (compat !== null && !compat.ok) {
1437
+ return { ok: false, from: current, to: version, reason: { code: 'compatBlocked', args: [version, compat.range, compat.dsh] } }
1438
+ }
1439
+ const runner = cliRunner()
1440
+ if (runner === null) return { ok: false, from: current, to: version, reason: { code: 'noCli' } }
1441
+ const lock = takeProfileLock(profileDir, new Date())
1442
+ if (!lock.ok) return { ok: false, from: current, to: version, reason: lock.reason }
1443
+ switching = { name: pkgName, version }
1444
+ try {
1445
+ writeLog('switching', [pkgName, current ?? '?', version])
1446
+ const outcome = await installOne(runner, profileName, profileDir, pkgName, version, settings.registry)
1447
+ if (!outcome.ok) return { ok: false, from: current, to: version, detail: outcome.detail ?? '' }
1448
+ clearFailure(pkgName, version)
1449
+ appendHistory({
1450
+ at: new Date().toISOString(),
1451
+ name: pkgName,
1452
+ from: current ?? '',
1453
+ to: version,
1454
+ tag: '',
1455
+ profile: profileName,
1456
+ rolledBack: false,
1457
+ })
1458
+ writeLog('switched', [pkgName, current ?? '?', version])
1459
+ // 切完就地换代码:和回滚同一条路径(requiredBefore 传空),不重启就能用上。
1460
+ let reload = null
1461
+ if (settings.hotReload) {
1462
+ reload = await hotApply(ctxRef.ctx, [])
1463
+ writeLog('reloaded', [reload?.status ?? 'none', reload?.reason ?? ''])
1464
+ }
1465
+ return { ok: true, from: current, to: version, detail: outcome.detail ?? '', reload: reload?.status ?? 'off' }
1466
+ } finally {
1467
+ switching = null
1468
+ releaseProfileLock(lock)
1469
+ }
1470
+ }
1093
1471
  function profileDirOf(ctx) {
1094
1472
  const base = propOf(serviceOf(ctx, 'hmr'), 'baseDir')
1095
1473
  if (typeof base === 'string' && base !== '') return base
@@ -1195,18 +1573,19 @@ function installedVersion(profileDir, pkgName, spec) {
1195
1573
  const tagCache = new Map()
1196
1574
  const TAG_TTL_MS = 10 * 60 * 1000
1197
1575
 
1198
- function tagCacheGet(pkgName) {
1199
- const hit = tagCache.get(pkgName)
1576
+ /** 缓存键带上源:同一个包在两个源上的答案可以不一样,不能混用。 */
1577
+ function tagCacheGet(key) {
1578
+ const hit = tagCache.get(key)
1200
1579
  if (hit === undefined) return null
1201
1580
  if (Date.now() - hit.at > TAG_TTL_MS) {
1202
- tagCache.delete(pkgName)
1581
+ tagCache.delete(key)
1203
1582
  return null
1204
1583
  }
1205
1584
  return hit.tags
1206
1585
  }
1207
1586
 
1208
- function tagCacheSet(pkgName, tags) {
1209
- tagCache.set(pkgName, { at: Date.now(), tags })
1587
+ function tagCacheSet(key, tags) {
1588
+ tagCache.set(key, { at: Date.now(), tags })
1210
1589
  // 缓存不设上限会随着 profile 换包一直长;几百个包就够用,超出就丢最旧的。
1211
1590
  if (tagCache.size > 400) {
1212
1591
  const oldest = tagCache.keys().next()
@@ -1214,18 +1593,20 @@ function tagCacheSet(pkgName, tags) {
1214
1593
  }
1215
1594
  }
1216
1595
 
1217
- async function registryTags(pkgName) {
1218
- const cached = tagCacheGet(pkgName)
1596
+ async function registryTags(pkgName, base = OFFICIAL_REGISTRY) {
1597
+ const key = base + '|' + pkgName
1598
+ const cached = tagCacheGet(key)
1219
1599
  if (cached !== null) return cached
1220
- const url = 'https://registry.npmjs.org/-/package/' + pkgName.replace('/', '%2f') + '/dist-tags'
1600
+ const url = base + '/-/package/' + pkgName.replace('/', '%2f') + '/dist-tags'
1221
1601
  const response = await fetch(url, {
1222
1602
  headers: { accept: 'application/json' },
1223
- signal: AbortSignal.timeout(10000),
1603
+ // 镜像慢起来很慢,但一个页面不该被它拖住:8 秒拿不到就回报失败。
1604
+ signal: AbortSignal.timeout(base === OFFICIAL_REGISTRY ? 10000 : 8000),
1224
1605
  })
1225
1606
  if (!response.ok) throw new Error('registry ' + response.status)
1226
1607
  const tags = await response.json()
1227
1608
  if (tags === null || typeof tags !== 'object') throw new Error('没有 dist-tags')
1228
- tagCacheSet(pkgName, tags)
1609
+ tagCacheSet(key, tags)
1229
1610
  return tags
1230
1611
  }
1231
1612
  /**
@@ -1304,11 +1685,15 @@ function runOnce(command, args, options) {
1304
1685
  })
1305
1686
  }
1306
1687
 
1307
- async function installOne(runner, profileName, profileDir, pkgName, version) {
1688
+ async function installOne(runner, profileName, profileDir, pkgName, version, registry = '') {
1308
1689
  const args = [...runner.prefix, 'plugin', '--profile', profileName, 'add', pkgName + '@' + version]
1690
+ // 选了安装源就让 pnpm 也走这个源:npm_config_registry 是 pnpm 也认的变量,
1691
+ // 只作用于这个子进程,不动 profile 的 .npmrc,也不动 pnpm 自己的配置。
1692
+ const env = { ...runner.env, CI: '1' }
1693
+ if (registry !== '') env.npm_config_registry = registry
1309
1694
  const result = await runOnce(runner.command, args, {
1310
1695
  cwd: profileDir,
1311
- env: { ...runner.env, CI: '1' },
1696
+ env,
1312
1697
  shell: runner.shell === true,
1313
1698
  timeoutMs: INSTALL_TIMEOUT_MS,
1314
1699
  })
@@ -1745,6 +2130,9 @@ async function runCycle(mode, ctxRef) {
1745
2130
  report.reason = { code: 'noDeps' }
1746
2131
  return report
1747
2132
  }
2133
+ // 镜像落后 / 兼容性拦下的明细:这一轮结束后写进 lastRun,界面按名字展示。
2134
+ const lagged = []
2135
+ const blocked = []
1748
2136
  for (let i = 0; i < deps.length; i += FETCH_CONCURRENCY) {
1749
2137
  // 每批之间让出一次事件循环:同步读 package.json 和结果合批都在主线程上,
1750
2138
  // 一口气跑完 24 个包会让界面掉帧。setImmediate 只让一次,代价可以忽略。
@@ -1753,9 +2141,17 @@ async function runCycle(mode, ctxRef) {
1753
2141
  const answers = await Promise.all(batch.map(async (dep) => {
1754
2142
  const current = installedVersion(profileDir, dep.name, dep.spec)
1755
2143
  try {
1756
- const tags = await registryTags(dep.name)
2144
+ // 换了源就按那个源查:缓存键带 base,两个源的答案不会串。
2145
+ const tags = await registryTags(dep.name, tagsBaseOf(settings.registry))
1757
2146
  const tag = distTagFor(dep.name)
1758
2147
  const target = typeof tags[tag] === 'string' ? tags[tag] : null
2148
+ // 用了镜像时顺手比一次官方源。它不改变这一轮的判断,但「已经是最新」
2149
+ // 这时候可能是假的——镜像没同步,官方源其实已经发了新版本。
2150
+ const lag = await mirrorLagOf(dep.name, settings.registry, tags)
2151
+ if (lag !== null) {
2152
+ lagged.push({ name: dep.name, installed: current, ...lag })
2153
+ writeLog('mirrorLag', [dep.name, lag.upstream, lag.mirror])
2154
+ }
1759
2155
  if (target === null) return { name: dep.name, current, why: { code: 'noTag', args: [tag] } }
1760
2156
  if (current === null) return { name: dep.name, current, why: { code: 'noInstalled' } }
1761
2157
  const verdict = upgradeVerdict(target, current, tag, settings)
@@ -1764,6 +2160,16 @@ async function runCycle(mode, ctxRef) {
1764
2160
  if (verdict.code === 'latest') return null
1765
2161
  return { name: dep.name, current, target, why: verdict.why }
1766
2162
  }
2163
+ // 兼容性预检:宿主闸门要等 bundle 卸下之后才拒绝,那时候快照已经白拍了、
2164
+ // 插件也处于「卸了一半」的样子。这里先问一句,装不了就不进队列。
2165
+ if (settings.compatCheck) {
2166
+ const compat = await compatOf(dep.name, target, settings.registry)
2167
+ if (compat !== null && !compat.ok) {
2168
+ blocked.push({ name: dep.name, target, need: compat.range, dsh: compat.dsh, from: compat.from })
2169
+ writeLog('compatBlocked', [dep.name, target, compat.range, compat.dsh])
2170
+ return { name: dep.name, current, target, why: { code: 'compatBlocked', args: [target, compat.range, compat.dsh] } }
2171
+ }
2172
+ }
1767
2173
  // 这个版本之前装失败过、还在抑制窗口内:这一轮不再试它。
1768
2174
  const until = suppressedUntil(dep.name, target, settings, new Date())
1769
2175
  if (until !== null) {
@@ -1787,6 +2193,8 @@ async function runCycle(mode, ctxRef) {
1787
2193
  else report.skipped.push(answer)
1788
2194
  }
1789
2195
  }
2196
+ report.lagged = lagged
2197
+ report.blocked = blocked
1790
2198
  writeLog('checked', [report.checked, report.updates.length])
1791
2199
  if (report.updates.length === 0) {
1792
2200
  report.reason = { code: 'noUpdates' }
@@ -1852,6 +2260,9 @@ async function runCycle(mode, ctxRef) {
1852
2260
  status: report.status,
1853
2261
  at: report.finishedAt,
1854
2262
  checked: report.checked,
2263
+ // 这一轮「镜像落后」与「兼容性拦下」的明细:界面要能指着名字说清为什么。
2264
+ lagged: Array.isArray(report.lagged) ? report.lagged : [],
2265
+ blocked: Array.isArray(report.blocked) ? report.blocked : [],
1855
2266
  // 结构化存:界面要分开排「包名」和「版本」,句子做不到。
1856
2267
  updates: report.updates.map((item) => ({ name: item.name, from: item.current ?? '', to: item.target })),
1857
2268
  installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' !failed')),
@@ -1886,7 +2297,7 @@ async function applyUpdates(ctxRef, report, settings, runner, profileDir, profil
1886
2297
  slowTimer.unref?.()
1887
2298
  let outcome
1888
2299
  try {
1889
- outcome = await installOne(runner, profileName, profileDir, update.name, update.target)
2300
+ outcome = await installOne(runner, profileName, profileDir, update.name, update.target, settings.registry)
1890
2301
  } finally {
1891
2302
  clearTimeout(slowTimer)
1892
2303
  }
@@ -1988,7 +2399,7 @@ async function rollbackOne(ctxRef, entryName) {
1988
2399
  if (!lock.ok) return { ok: false, reason: lock.reason }
1989
2400
  let outcome
1990
2401
  try {
1991
- outcome = await installOne(runner, profileName, profileDir, row.name, row.from)
2402
+ outcome = await installOne(runner, profileName, profileDir, row.name, row.from, settings.registry)
1992
2403
  } finally {
1993
2404
  releaseProfileLock(lock)
1994
2405
  }
@@ -2205,6 +2616,10 @@ function settingsSnapshot(config, ctxRef, lang) {
2205
2616
  overrides: readOverrides(),
2206
2617
  // 「关于 aupdate」显示用;随 package.json 自动更新,无需手改前端。
2207
2618
  version: pluginVersion,
2619
+ // 这台宿主真正在跑的 DSH 版本:兼容性预检就是按它比的,界面也要能看见它。
2620
+ dshVersion: dshVersion(),
2621
+ // 生效的安装源('' = 跟随 pnpm)。
2622
+ registry: settings.registry,
2208
2623
  // 运行中的进度:没在跑时为 null,设置页据此决定要不要显示进度条。
2209
2624
  progress: progress === null ? null : { ...progress },
2210
2625
  lastRun: lastRun === null ? null : {
@@ -2214,6 +2629,8 @@ function settingsSnapshot(config, ctxRef, lang) {
2214
2629
  checked: lastRun.checked,
2215
2630
  updates: lastRun.updates,
2216
2631
  installed: lastRun.installed,
2632
+ lagged: Array.isArray(lastRun.lagged) ? lastRun.lagged : [],
2633
+ blocked: Array.isArray(lastRun.blocked) ? lastRun.blocked : [],
2217
2634
  reload: lastRun.reload,
2218
2635
  snapshot: lastRun.snapshot ?? '',
2219
2636
  },
@@ -2296,6 +2713,23 @@ function registerRoutes(scope, ctxRef) {
2296
2713
  sendJson(res, 200, readLogTail(url.searchParams.get('lines'), url.searchParams.get('lang')))
2297
2714
  return
2298
2715
  }
2716
+ if (suffix === '/versions') {
2717
+ // 一次只看一个包的版本列表:整页一次拉一排包,镜像上会很慢。
2718
+ const target = url.searchParams.get('name') ?? ''
2719
+ if (target === '') {
2720
+ sendJson(res, 400, { error: 'missing name' })
2721
+ return
2722
+ }
2723
+ try {
2724
+ const live = settingsOf(ctxRef.config)
2725
+ const listed = await publishedVersions(target, live.registry)
2726
+ const profileDir = profileDirOf(ctxRef.ctx)
2727
+ sendJson(res, 200, { ...listed, installed: installedVersion(profileDir, target, null) })
2728
+ } catch (error) {
2729
+ sendJson(res, 502, { error: oneLine(error?.message ?? error, 200) })
2730
+ }
2731
+ return
2732
+ }
2299
2733
  sendJson(res, 404, { error: 'unknown endpoint' })
2300
2734
  return
2301
2735
  }
@@ -2321,6 +2755,21 @@ function registerRoutes(scope, ctxRef) {
2321
2755
  sendJson(res, 200, settingsSnapshot(ctxRef.config, ctxRef, url.searchParams.get('lang')))
2322
2756
  return
2323
2757
  }
2758
+ if (suffix === '/switch') {
2759
+ const body = await readBody(req)
2760
+ const target = typeof body?.name === 'string' ? body.name : ''
2761
+ const version = typeof body?.version === 'string' ? body.version : ''
2762
+ if (target === '' || version === '') {
2763
+ sendJson(res, 400, { error: 'missing name or version' })
2764
+ return
2765
+ }
2766
+ const outcome = await switchVersion(ctxRef, target, version)
2767
+ sendJson(res, outcome.ok ? 200 : 409, {
2768
+ ...outcome,
2769
+ reason: outcome.reason === undefined ? '' : renderReason(outcome.reason, url.searchParams.get('lang')),
2770
+ })
2771
+ return
2772
+ }
2324
2773
  if (suffix === '/rollback') {
2325
2774
  const body = await readBody(req)
2326
2775
  const target = typeof body?.name === 'string' ? body.name : ''
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aupdate",
3
- "version": "0.7.4",
3
+ "version": "0.7.5",
4
4
  "type": "module",
5
5
  "description": "定时检查 DSH 插件更新,串行安装后就地生效,不重启;支持多种调度节奏、失败抑制、按包回滚,并在动手前留快照、忙时自动让开;不更新/只更新哪些插件改成勾选,发现更新在右下角提醒,日志最新在最上面,并在「设置 → 插件更新」里有独立一页。",
6
6
  "license": "MIT",
@@ -21,7 +21,8 @@
21
21
  "index.js",
22
22
  "client.js",
23
23
  "cordis.patch.yml",
24
- "README.md"
24
+ "README.md",
25
+ "docs"
25
26
  ],
26
27
  "engines": {
27
28
  "dsh": ">=0.2.0-rc.1"