yukari-dsh-plugin 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -2
  3. package/client.js +8340 -0
  4. package/cordis.patch.yml +95 -0
  5. package/host/browser/index.js +397 -0
  6. package/host/browser/lib/browser.js +885 -0
  7. package/host/browser/lib/cdp.js +302 -0
  8. package/host/browser/lib/libraries.js +309 -0
  9. package/host/browser/lib/page-scripts.js +243 -0
  10. package/host/browser/lib/runtime.js +351 -0
  11. package/host/browser/lib/url-guard.js +122 -0
  12. package/host/browser/locale/en.json +6 -0
  13. package/host/browser/locale/zh.json +6 -0
  14. package/host/chats/index.js +254 -0
  15. package/host/chats/lib/admin.js +893 -0
  16. package/host/chats/lib/cleanup.js +272 -0
  17. package/host/chats/lib/paths.js +108 -0
  18. package/host/chats/lib/preview.js +74 -0
  19. package/host/chats/locale/en.json +6 -0
  20. package/host/chats/locale/zh.json +6 -0
  21. package/host/files/index.js +403 -0
  22. package/host/files/locale/en.json +6 -0
  23. package/host/files/locale/zh.json +6 -0
  24. package/host/github/index.js +121 -0
  25. package/host/github/lib/api.js +310 -0
  26. package/host/github/lib/atomic.js +42 -0
  27. package/host/github/lib/controller.js +450 -0
  28. package/host/github/lib/git.js +389 -0
  29. package/host/github/lib/redact.js +22 -0
  30. package/host/github/lib/signing.js +124 -0
  31. package/host/github/lib/store.js +181 -0
  32. package/host/github/locale/en.json +6 -0
  33. package/host/github/locale/zh.json +6 -0
  34. package/host/presets/index.js +450 -0
  35. package/host/presets/lib/definition.js +267 -0
  36. package/host/presets/lib/sources.js +278 -0
  37. package/host/presets/lib/store.js +136 -0
  38. package/host/presets/locale/en.json +6 -0
  39. package/host/presets/locale/zh.json +6 -0
  40. package/host/proxy/index.js +236 -0
  41. package/host/proxy/lib/controller.js +1151 -0
  42. package/host/proxy/lib/egress.js +120 -0
  43. package/host/proxy/lib/local-proxy.js +422 -0
  44. package/host/proxy/lib/shadowsocks.js +335 -0
  45. package/host/proxy/lib/ss-uri.js +501 -0
  46. package/host/proxy/lib/subscriptions.js +140 -0
  47. package/host/proxy/locale/en.json +6 -0
  48. package/host/proxy/locale/zh.json +6 -0
  49. package/host/purge/index.js +538 -0
  50. package/host/purge/lib/preset.js +140 -0
  51. package/host/purge/lib/prompts.js +95 -0
  52. package/host/purge/lib/retry-gate.js +97 -0
  53. package/host/purge/lib/rewriter.js +322 -0
  54. package/host/purge/lib/settings.js +54 -0
  55. package/host/purge/lib/stream-retry.js +255 -0
  56. package/host/purge/locale/en.json +6 -0
  57. package/host/purge/locale/zh.json +6 -0
  58. package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
  59. package/host/purge/presets/unrestricted/preset.json +75 -0
  60. package/host/purge/presets/unrestricted/preset.yml +3 -0
  61. package/host/rewind/index.js +127 -0
  62. package/host/rewind/lib/controller.js +449 -0
  63. package/host/rewind/lib/marker.js +53 -0
  64. package/host/rewind/lib/safe-path.js +47 -0
  65. package/host/rewind/lib/store.js +585 -0
  66. package/host/rewind/lib/surface.js +108 -0
  67. package/host/rewind/locale/en.json +6 -0
  68. package/host/rewind/locale/zh.json +6 -0
  69. package/host/rules/index.js +624 -0
  70. package/host/rules/lib/paths.js +87 -0
  71. package/host/rules/lib/render.js +92 -0
  72. package/host/rules/lib/scope.js +146 -0
  73. package/host/rules/lib/settings.js +55 -0
  74. package/host/rules/lib/store.js +222 -0
  75. package/host/rules/locale/en.json +6 -0
  76. package/host/rules/locale/zh.json +6 -0
  77. package/host/runtime/index.js +577 -0
  78. package/host/runtime/lib/npm.js +293 -0
  79. package/host/runtime/lib/restart.js +105 -0
  80. package/host/runtime/lib/update-guard.js +70 -0
  81. package/host/runtime/lib/versions.js +188 -0
  82. package/host/runtime/locale/en.json +6 -0
  83. package/host/runtime/locale/zh.json +6 -0
  84. package/host/shared/busy.js +40 -0
  85. package/host/shared/home.js +27 -0
  86. package/host/shared/http.js +159 -0
  87. package/host/shared/migrate.js +60 -0
  88. package/host/shared/mounted.js +54 -0
  89. package/host/shared/zip-writer.js +319 -0
  90. package/host/shared/zip.js +180 -0
  91. package/host/sites/index.js +258 -0
  92. package/host/sites/lib/sites.js +630 -0
  93. package/host/sites/locale/en.json +6 -0
  94. package/host/sites/locale/zh.json +6 -0
  95. package/host/skills/index.js +176 -0
  96. package/host/skills/lib/frontmatter.js +149 -0
  97. package/host/skills/lib/library.js +408 -0
  98. package/host/skills/lib/upload.js +115 -0
  99. package/host/skills/locale/en.json +6 -0
  100. package/host/skills/locale/zh.json +6 -0
  101. package/icon.png +0 -0
  102. package/index.js +702 -0
  103. package/locale/en.json +5 -0
  104. package/locale/zh.json +5 -0
  105. package/package.json +113 -4
package/index.js ADDED
@@ -0,0 +1,702 @@
1
+ /**
2
+ * Yukari 插件合集 — 主行。
3
+ *
4
+ * 各组件由 `cordis.patch.yml` 里各自独立的行挂载(`yukari-dsh-plugin/<name>`),
5
+ * 在插件管理里可以单独开关。主行只负责面板需要的公共接口:
6
+ *
7
+ * - `GET /yukari/api/overview` 版本与各组件的启用状态;
8
+ * - `GET /yukari/api/update` 检查插件是否有新版本;
9
+ * - `POST /yukari/api/update` 有新版本时更新插件;
10
+ * - `POST /yukari/api/restart` 运行时组件关闭时的重启兜底;
11
+ * - `GET /yukari/api/icon` 面板与侧边栏图标。
12
+ *
13
+ * 主行不再代为挂载子组件:子组件只由自己的行挂载,避免同一路由被注册两次。
14
+ * @module yukari-dsh-plugin
15
+ */
16
+ import { execFile } from 'node:child_process'
17
+ import { randomUUID } from 'node:crypto'
18
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
19
+ import { createRequire } from 'node:module'
20
+ import { hostname } from 'node:os'
21
+ import path from 'node:path'
22
+ import { fileURLToPath, pathToFileURL } from 'node:url'
23
+ import { promisify } from 'node:util'
24
+ import { planRestart, scheduleRestart } from './host/runtime/lib/restart.js'
25
+ import { compare, isVersionText } from './host/runtime/lib/versions.js'
26
+ import { mountedComponents } from './host/shared/mounted.js'
27
+ import { appError, guardRoute, messageOf, readJsonBody, sendJson } from './host/shared/http.js'
28
+ import { busyLabel, runExclusive } from './host/shared/busy.js'
29
+ import { resolveDshHome } from './host/shared/home.js'
30
+ import { acquireUpdateLock } from './host/runtime/lib/update-guard.js'
31
+
32
+ const execFileAsync = promisify(execFile)
33
+ const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url))
34
+ const PACKAGE_NAME = 'yukari-dsh-plugin'
35
+ const DEFAULT_REPO = { owner: 'Yukari-Lily', repo: 'Yukari-dsh-plugin', ref: '' }
36
+
37
+ /** Read-only endpoint prefix the panel calls. */
38
+ export const API_PATH = '/yukari/api'
39
+
40
+ /** Services the main row needs. */
41
+ export const inject = ['webServer', 'connection', 'pluginManager']
42
+
43
+ /** Version of the code loaded in this process. */
44
+ function packageVersion(dir = PLUGIN_DIR) {
45
+ try {
46
+ const pkg = JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8'))
47
+ return typeof pkg.version === 'string' ? pkg.version : '0.0.0'
48
+ } catch {
49
+ return '0.0.0'
50
+ }
51
+ }
52
+
53
+ const RUNNING_VERSION = packageVersion()
54
+
55
+ /** 模块会被 HMR 重新执行,进程标识必须挂在进程级对象上;execve 后才会重新生成。 */
56
+ const BOOT_KEY = Symbol.for('yukari-dsh-plugin.boot-id')
57
+ const BOOT_ID = (globalThis[BOOT_KEY] ??= randomUUID())
58
+
59
+
60
+ /* ------------------------------------------------------------- install info */
61
+
62
+ /** Parse a pnpm/npm git spec into GitHub coordinates, or null. */
63
+ export function parseRepoSpec(spec) {
64
+ const text = String(spec ?? '').trim()
65
+ if (text === '') return null
66
+ const hash = text.indexOf('#')
67
+ const ref = hash === -1 ? '' : text.slice(hash + 1).replace(/^semver:.*/, '')
68
+ const body = hash === -1 ? text : text.slice(0, hash)
69
+ const match =
70
+ /^(?:github:)?([\w.-]+)\/([\w.-]+?)(?:\.git)?$/.exec(body) ??
71
+ /github\.com[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(body)
72
+ if (match === null) return null
73
+ // 完整 SHA 只固定本次安装;更新检查仍跟踪默认分支,否则迁移后再也找不到新版。
74
+ return { owner: match[1], repo: match[2], ref: /^[0-9a-f]{40}$/iu.test(ref) ? '' : ref }
75
+ }
76
+
77
+ /** Where this copy came from and how it can be updated. */
78
+ function locateInstall() {
79
+ if (existsSync(path.join(PLUGIN_DIR, '.git'))) return { kind: 'git', dir: PLUGIN_DIR, repo: DEFAULT_REPO }
80
+ let real = PLUGIN_DIR
81
+ try {
82
+ real = realpathSync(PLUGIN_DIR)
83
+ } catch {
84
+ real = PLUGIN_DIR
85
+ }
86
+ const parts = real.split(path.sep)
87
+ const index = parts.indexOf('node_modules')
88
+ if (index > 0) {
89
+ const profileDir = parts.slice(0, index).join(path.sep) || path.sep
90
+ try {
91
+ const manifest = JSON.parse(readFileSync(path.join(profileDir, 'package.json'), 'utf8'))
92
+ const spec = manifest.dependencies?.[PACKAGE_NAME]
93
+ if (typeof spec === 'string' && spec !== '') {
94
+ return { kind: 'profile', profileDir, spec, repo: parseRepoSpec(spec), real }
95
+ }
96
+ } catch {
97
+ // not a profile directory
98
+ }
99
+ }
100
+ return { kind: 'unknown', real }
101
+ }
102
+
103
+ /**
104
+ * 安装来源的种类。
105
+ *
106
+ * 只有 `github` 的副本能自己去问仓库;npm 包、安装包、本地目录、别家 Git 托管的副本
107
+ * 都只能由人装新版,更新检查不该拿它们去问一个写死的仓库。
108
+ *
109
+ * @param spec - profile 里保存的依赖规格。
110
+ * @returns 来源种类。
111
+ */
112
+ export function installSourceKind(spec) {
113
+ const text = String(spec ?? '').trim()
114
+ if (text === '') return 'unknown'
115
+ if (parseRepoSpec(text) !== null) return 'github'
116
+ const tarball = /\.(?:tgz|tar\.gz)(?:#.*)?$/iu.test(text)
117
+ if (/^(?:file|link):/iu.test(text) || path.isAbsolute(text)) return tarball ? 'tarball' : 'path'
118
+ if (tarball) return 'tarball'
119
+ if (/^(?:github|gitlab|bitbucket|gist):|^git(?:\+[a-z]+)?:\/\//iu.test(text) || /^git@[^:]+:/iu.test(text) || /^https?:\/\//iu.test(text)) {
120
+ return 'git'
121
+ }
122
+ return 'registry'
123
+ }
124
+
125
+ /**
126
+ * 这份安装的来源,以及它能否自己更新。
127
+ * @param install - {@link locateInstall} 的结果。
128
+ * @returns 来源种类、能否自动更新、GitHub 坐标(不可自动更新时为 null)与原始规格。
129
+ */
130
+ export function installSource(install) {
131
+ const kind = install.kind === 'git' ? 'github' : install.kind === 'profile' ? installSourceKind(install.spec) : 'unknown'
132
+ // 只有本机 checkout 没有规格可读,才用写死的仓库;profile 安装一律以保存的规格为准。
133
+ const repo = install.kind === 'git' ? (install.repo ?? DEFAULT_REPO) : kind === 'github' ? parseRepoSpec(install.spec) : null
134
+ const source = install.kind === 'profile' ? String(install.spec ?? '') : repo === null ? '' : `${repo.owner}/${repo.repo}`
135
+ return { kind, updatable: repo !== null, repo, source }
136
+ }
137
+
138
+ /** Commit of the installed copy: from the lockfile, else from the pnpm store path. */
139
+ function installedCommit(install) {
140
+ if (install.kind === 'profile') {
141
+ try {
142
+ const lock = readFileSync(path.join(install.profileDir, 'pnpm-lock.yaml'), 'utf8')
143
+ const pattern = new RegExp(`${install.repo.repo}[^\\n]*?([0-9a-f]{40})`, 'i')
144
+ const found = pattern.exec(lock)
145
+ if (found !== null) return found[1].toLowerCase()
146
+ } catch {
147
+ // no lockfile
148
+ }
149
+ }
150
+ const fromPath = /([0-9a-f]{40})/i.exec(install.real ?? '')
151
+ return fromPath === null ? null : fromPath[1].toLowerCase()
152
+ }
153
+
154
+ /** Commit the running copy was loaded from (never changes until a restart). */
155
+ const RUNNING_COMMIT = (() => {
156
+ try {
157
+ return installedCommit(locateInstall())
158
+ } catch {
159
+ return null
160
+ }
161
+ })()
162
+
163
+ /** Fetch one URL with a timeout. */
164
+ async function fetchWithTimeout(url, ms, init = {}) {
165
+ const controller = new AbortController()
166
+ const timer = setTimeout(() => controller.abort(), ms)
167
+ try {
168
+ return await fetch(url, { ...init, signal: controller.signal })
169
+ } finally {
170
+ clearTimeout(timer)
171
+ }
172
+ }
173
+
174
+ /** Newest commit of the tracked branch. */
175
+ async function remoteCommit(repo) {
176
+ const ref = repo.ref === '' ? 'HEAD' : repo.ref
177
+ try {
178
+ const { stdout } = await execFileAsync('git', ['ls-remote', `https://github.com/${repo.owner}/${repo.repo}.git`, ref], {
179
+ timeout: 15000,
180
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
181
+ })
182
+ const match = /^([0-9a-f]{40})/im.exec(stdout)
183
+ if (match !== null) return match[1].toLowerCase()
184
+ } catch {
185
+ // fall back to the API
186
+ }
187
+ try {
188
+ const response = await fetchWithTimeout(`https://api.github.com/repos/${repo.owner}/${repo.repo}/commits/${encodeURIComponent(ref)}`, 10000, {
189
+ headers: { accept: 'application/vnd.github+json', 'user-agent': PACKAGE_NAME },
190
+ })
191
+ if (response.ok) {
192
+ const body = await response.json()
193
+ if (typeof body?.sha === 'string') return body.sha.toLowerCase()
194
+ }
195
+ } catch {
196
+ // unreachable
197
+ }
198
+ return null
199
+ }
200
+
201
+ /** `version` of package.json at one commit or ref. */
202
+ async function remoteVersion(repo, at) {
203
+ const ref = at ?? (repo.ref === '' ? 'HEAD' : repo.ref)
204
+ const urls = [
205
+ `https://raw.githubusercontent.com/${repo.owner}/${repo.repo}/${ref}/package.json`,
206
+ `https://cdn.jsdelivr.net/gh/${repo.owner}/${repo.repo}@${ref}/package.json`,
207
+ ]
208
+ for (const url of urls) {
209
+ try {
210
+ const response = await fetchWithTimeout(url, 10000, { headers: { 'user-agent': PACKAGE_NAME } })
211
+ if (!response.ok) continue
212
+ const body = await response.json()
213
+ if (typeof body?.version === 'string') return body.version
214
+ } catch {
215
+ // try the next mirror
216
+ }
217
+ }
218
+ return null
219
+ }
220
+
221
+ /** Proxy variables a child process may use to reach the network. */
222
+ const EGRESS_NAMES = ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy']
223
+
224
+ /** Host names that mean "this machine's own proxy" rather than an operator's proxy. */
225
+ const LOOPBACK_NAMES = new Set(['127.0.0.1', 'localhost', '::1'])
226
+
227
+ /**
228
+ * The environment a child gets when the update must reach the network on its
229
+ * own: the process environment without any proxy names.
230
+ *
231
+ * @returns a fresh environment object.
232
+ */
233
+ export function directChildEnv() {
234
+ const env = { ...process.env }
235
+ for (const name of EGRESS_NAMES) Reflect.deleteProperty(env, name)
236
+ Reflect.deleteProperty(env, 'NODE_USE_ENV_PROXY')
237
+ return env
238
+ }
239
+
240
+ /**
241
+ * Clear the Host's own launch-time proxy policy when it points at this
242
+ * plugin's loopback listener.
243
+ *
244
+ * A restart while the route is enabled bakes `HTTP_PROXY=http://127.0.0.1:<port>`
245
+ * into the Host's launch environment. DSH remembers that as its proxy policy and
246
+ * re-publishes it into every child it spawns — clearing `process.env` alone does
247
+ * not reach those children. Installing a direct policy through the same module
248
+ * instance the Host uses is the only way to release it from inside a plugin.
249
+ *
250
+ * The host package is resolved from the running CLI entry, so this works on any
251
+ * install; a Host that cannot be reached this way simply keeps its policy and the
252
+ * update's direct-network preflight decides whether proceeding is safe.
253
+ *
254
+ * @returns whether a direct policy was installed.
255
+ */
256
+ export async function releaseHostProxyPolicy() {
257
+ try {
258
+ const hostEntry = process.argv[1]
259
+ if (typeof hostEntry !== 'string' || hostEntry === '') return false
260
+ const requireFromHost = createRequire(hostEntry)
261
+ const modulePath = requireFromHost.resolve('@deepseek-ai/dsh-http-proxy')
262
+ const hostProxy = await import(pathToFileURL(modulePath).href)
263
+ if (typeof hostProxy.installProxyFromEnvironment !== 'function' || typeof hostProxy.proxyRouteFor !== 'function') return false
264
+ // Only a policy that routes through this machine's loopback listener is ours
265
+ // to drop; an operator-set proxy must survive.
266
+ const route = hostProxy.proxyRouteFor(new URL('https://github.com/'))
267
+ if (route?.proxied !== true || typeof route.proxy !== 'string') return false
268
+ const host = new URL(route.proxy).hostname.replace(/^\[|\]$/g, '').toLowerCase()
269
+ if (!LOOPBACK_NAMES.has(host)) return false
270
+ // An empty launch environment resolves to the direct policy. The disposer is
271
+ // deliberately dropped: the route must stay direct through the update.
272
+ await hostProxy.installProxyFromEnvironment({ get: () => undefined }, () => {})
273
+ return true
274
+ } catch {
275
+ return false
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Refuse an update whose installer would have no way back to GitHub.
281
+ *
282
+ * The old copy is removed before the new one is installed. When the install
283
+ * cannot reach GitHub directly, that step fails and the network-based rollback
284
+ * fails with it, leaving an empty profile. This check runs while the old copy is
285
+ * still installed, with the proxy names stripped, so it measures exactly the
286
+ * network the installer will have after removal.
287
+ *
288
+ * @param repo - owner and repository of the installed copy.
289
+ * @param run - process runner, replaceable by tests.
290
+ * @throws when direct access fails.
291
+ */
292
+ export async function assertDirectGithub(repo, run = execFileAsync) {
293
+ const url = `https://github.com/${repo.owner}/${repo.repo}.git`
294
+ try {
295
+ await run('git', ['ls-remote', '--heads', url], { timeout: 20000, env: directChildEnv() })
296
+ } catch (error) {
297
+ const detail = messageOf(error).split('\n')[0]
298
+ throw new Error(`直连 GitHub 失败,已取消更新以免卸载旧版后装不回来(${detail});请检查直连网络后重试`)
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Drop proxy variables that point at this plugin's own loopback listener.
304
+ *
305
+ * The host hands its children the environment it booted with. Once an update
306
+ * removes the proxy component, `git` and `pnpm` behind the installer still dial
307
+ * the now-closed loopback port and the update fails after the old copy is
308
+ * already gone. Clearing these variables first lets the installer go direct.
309
+ * Only loopback values are touched, so an operator-set proxy survives.
310
+ *
311
+ * @returns the names that were cleared.
312
+ */
313
+ export function releaseLocalEgress() {
314
+ const cleared = []
315
+ for (const name of EGRESS_NAMES) {
316
+ const value = process.env[name]
317
+ if (typeof value !== 'string' || value.length === 0) continue
318
+ let url
319
+ try {
320
+ url = new URL(value)
321
+ } catch {
322
+ continue
323
+ }
324
+ const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase()
325
+ if (!LOOPBACK_NAMES.has(host)) continue
326
+ Reflect.deleteProperty(process.env, name)
327
+ cleared.push(name)
328
+ }
329
+ if (cleared.length === 0) return cleared
330
+ // Node's built-in fetch reads this to decide whether to honour the variables.
331
+ Reflect.deleteProperty(process.env, 'NODE_USE_ENV_PROXY')
332
+ return cleared
333
+ }
334
+
335
+ /**
336
+ * Compare the running copy with the newest commit of its branch.
337
+ *
338
+ * 只有 GitHub 来源的副本才有仓库可比:npm 包、安装包、本地目录的副本没有远端版本可问,
339
+ * 拿写死的仓库去问只会得到一个对方装不回来的新版,所以这些来源直接报告"要人装新版"。
340
+ */
341
+ async function checkUpdate() {
342
+ const install = locateInstall()
343
+ const source = installSource(install)
344
+ const onDisk = packageVersion()
345
+ const base = {
346
+ current: RUNNING_VERSION,
347
+ installed: onDisk,
348
+ installDir: install.kind === 'profile' ? install.profileDir : PLUGIN_DIR,
349
+ restartSupported: process.platform !== 'win32',
350
+ sourceKind: source.kind,
351
+ source: source.source,
352
+ checkedAt: new Date().toISOString(),
353
+ }
354
+ if (!source.updatable) {
355
+ return {
356
+ ...base,
357
+ latest: onDisk,
358
+ currentCommit: null,
359
+ latestCommit: null,
360
+ latestSha: null,
361
+ installedSha: null,
362
+ available: false,
363
+ pendingRestart: onDisk !== RUNNING_VERSION,
364
+ updatable: false,
365
+ }
366
+ }
367
+ const installed = installedCommit(install)
368
+ const latestCommit = await remoteCommit(source.repo)
369
+ const latestVersion = await remoteVersion(source.repo, latestCommit ?? undefined)
370
+ if (latestCommit === null && latestVersion === null) {
371
+ throw new Error('连不上 GitHub,无法检查更新(检查网络或在「代理」里启用节点)')
372
+ }
373
+ const newerVersion = latestVersion !== null && compare(latestVersion, onDisk) > 0
374
+ const newerCommit = latestCommit !== null && installed !== null && latestCommit !== installed
375
+ // Installed on disk but not loaded yet: the copy changed since this process started.
376
+ const pendingRestart =
377
+ onDisk !== RUNNING_VERSION || (installed !== null && RUNNING_COMMIT !== null && installed !== RUNNING_COMMIT)
378
+ return {
379
+ ...base,
380
+ latest: latestVersion ?? RUNNING_VERSION,
381
+ currentCommit: (RUNNING_COMMIT ?? installed)?.slice(0, 7) ?? null,
382
+ latestCommit: latestCommit?.slice(0, 7) ?? null,
383
+ latestSha: latestCommit,
384
+ installedSha: installed,
385
+ available: (newerVersion || newerCommit) && !(pendingRestart && latestCommit === installed),
386
+ pendingRestart,
387
+ updatable: true,
388
+ }
389
+ }
390
+
391
+ /** 固定完整 commit,官方更新器才能精确恢复旧版。 */
392
+ function pinnedSpec(repo, commit) {
393
+ if (!/^[0-9a-f]{40}$/u.test(String(commit ?? ''))) throw new Error('没有取得目标 commit,无法通过插件管理器更新')
394
+ return `github:${repo.owner}/${repo.repo}#${commit}`
395
+ }
396
+
397
+ /** 官方管理器会用返回值报告失败,不一定抛异常。 */
398
+ function managerFailed(result) {
399
+ return result?.application === 'failed' || result?.application === 'cancelled'
400
+ }
401
+
402
+ /** 同时保留目标失败原因和旧版恢复结果,避免只报一句更新失败。 */
403
+ function managerError(result, restore, note = '') {
404
+ const diagnostic = result?.error?.diagnostic ?? result?.error?.code ?? `插件管理器在 ${result?.stage ?? 'install'} 阶段失败`
405
+ let suffix = ''
406
+ if (restore !== undefined) {
407
+ suffix = managerFailed(restore)
408
+ ? ';旧版恢复失败'
409
+ : restore.application === 'restart-required' ? ';旧版已安装,重启后恢复' : ';已恢复旧版'
410
+ }
411
+ return new Error(`${diagnostic}${note === '' ? suffix : note}`)
412
+ }
413
+
414
+ /** 直接抛异常和返回失败值都必须进入旧版恢复路径。 */
415
+ async function managerSettled(operation) {
416
+ try {
417
+ return await operation()
418
+ } catch (error) {
419
+ return { application: 'failed', stage: 'install', error: { diagnostic: messageOf(error) } }
420
+ }
421
+ }
422
+
423
+ /** 把官方结果压缩成路由需要的版本与应用状态。 */
424
+ function managerApplied(result, fallbackVersion) {
425
+ if (managerFailed(result)) throw managerError(result)
426
+ return {
427
+ updated: result.changed !== false,
428
+ installed: result.version ?? fallbackVersion,
429
+ application: result.application,
430
+ restartReason: result.restartReason ?? null,
431
+ }
432
+ }
433
+
434
+ /**
435
+ * 与「插件」页共用同一个管理器。旧安装跟踪分支,移动的分支无法可靠恢复;
436
+ * 首次先迁移成固定 commit,之后由 updateBundle 负责兼容检查、替换和回滚。
437
+ */
438
+ export async function updateProfile(ctx, install, before, options = {}) {
439
+ if (!isVersionText(before.latest)) throw new Error('没有取得目标版本号,无法通过插件管理器更新')
440
+ const targetSpec = pinnedSpec(install.repo, before.latestSha)
441
+ const manager = ctx.pluginManager
442
+ const bundles = await manager.listBundles()
443
+ const current = bundles.find((item) => item.name === PACKAGE_NAME)
444
+ if (current === undefined) throw new Error('插件管理器找不到当前安装,请在「插件」页重新安装')
445
+
446
+ // 官方管理器的 updateBundle 要求目标版本严格大于已装版本(semver.gt),版本号回退——比如把历史
447
+ // 重写、版本重新编号——会被它直接拒绝。更新只认 commit,所以这种情况走「按固定 commit 移除再装」。
448
+ const newerVersion = compare(before.latest, before.installed ?? before.current ?? '0.0.0') > 0
449
+ if (current.update === 'git' && newerVersion) {
450
+ // 原地替换:插件全程留在盘上,本机代理监听器不中断,pnpm 与 git 可以继续走当前路由安装,
451
+ // 因此这里既不释放代理也不要求直连。只有下面要把旧版拿掉的路径才需要那样的前提。
452
+ const outcome = await manager.updateBundle(PACKAGE_NAME, before.latest, { spec: targetSpec })
453
+ if (managerFailed(outcome.result)) throw managerError(outcome.result, outcome.restore)
454
+ await verifyInstalled(manager, outcome.result)
455
+ return managerApplied(outcome.result, before.latest)
456
+ }
457
+
458
+ // 从这里开始旧版会被移出 profile,代理监听器也随之消失:先释放本机回环路由,
459
+ // 再证明直连可用,否则卸载之后既装不回新版,也回滚不了旧版。
460
+ await prepareRemoval(ctx, install, options)
461
+
462
+ // 固定 commit 会丢掉原分支名;非默认分支不能静默改成跟踪 HEAD。
463
+ if (install.repo.ref !== '') throw new Error('非默认分支请在「插件」页重新安装目标 commit,避免更新时切换分支')
464
+
465
+ // 没有 HMR 时官方管理器会覆盖安装并报告 restart-required;
466
+ // expected 同时校验实际落地的包和版本,不能只凭锁文件判断成功。
467
+ if (ctx.get('hmr') === undefined) {
468
+ const result = await managerSettled(() => manager.installBundle(targetSpec, {
469
+ enabled: current.enabled !== false,
470
+ expected: { name: PACKAGE_NAME, version: before.latest },
471
+ }))
472
+ const applied = managerApplied(result, before.latest)
473
+ await verifyInstalled(manager, result)
474
+ return applied
475
+ }
476
+
477
+ // 卸载之前先确认旧 commit 可恢复,不能等失败时才发现它未知。
478
+ const previous = pinnedSpec(install.repo, before.installedSha)
479
+ const removal = await manager.removeBundle(PACKAGE_NAME)
480
+ if (managerFailed(removal)) throw managerError(removal)
481
+ const enabled = current.enabled !== false
482
+ const result = await managerSettled(() => manager.installBundle(targetSpec, {
483
+ enabled,
484
+ expected: { name: PACKAGE_NAME, version: before.latest },
485
+ }))
486
+ if (managerFailed(result)) {
487
+ if (result.stage === 'enable') await managerSettled(() => manager.removeBundle(PACKAGE_NAME))
488
+ // 恢复实际运行过的 commit,不能恢复可能已经移动的旧分支。
489
+ const restore = await managerSettled(() => manager.installBundle(previous, { enabled }))
490
+ throw managerError(result, restore)
491
+ }
492
+ await verifyInstalled(manager, result)
493
+ return managerApplied(result, before.latest)
494
+ }
495
+
496
+ /**
497
+ * 把旧版移出 profile 之前,先把安装要走的路变成「不依赖本插件」。
498
+ *
499
+ * 卸载会把本机代理一起带走,宿主又把子进程的代理变量钉在启动时的值上:不先释放,
500
+ * pnpm 与 git 会一直拨那个已经关掉的回环端口。释放之后必须确认直连能用,否则
501
+ * 卸载之后既装不回新版,也回滚不了旧版。
502
+ *
503
+ * @param ctx - plugin context, for the log.
504
+ * @param install - {@link locateInstall} 的结果。
505
+ * @param options.preflight - 测试用的预检替身;只放在参数上,不读 Cordis 上下文。
506
+ */
507
+ async function prepareRemoval(ctx, install, options) {
508
+ const policyReleased = await releaseHostProxyPolicy()
509
+ const clearedEgress = releaseLocalEgress()
510
+ if (clearedEgress.length > 0 || policyReleased) {
511
+ try {
512
+ ctx.logger?.('yukari-update')?.warn?.(`released the local proxy route before updating (env: ${clearedEgress.join(', ') || 'none'}, host policy: ${policyReleased ? 'released' : 'unchanged'})`)
513
+ } catch {
514
+ // A missing logger must not stop the update.
515
+ }
516
+ }
517
+ const preflight = typeof options.preflight === 'function' ? options.preflight : () => assertDirectGithub(install.repo)
518
+ await preflight()
519
+ }
520
+
521
+ /**
522
+ * Check that the installed copy is actually registered and enabled.
523
+ *
524
+ * 校验失败只报告真实状态,不在目标包仍占用依赖时再装一份旧包;后者会被
525
+ * 官方管理器以 already-installed 拒绝,还会掩盖最初的注册问题。
526
+ *
527
+ * `installed` 只表示 profile 声明了依赖,`enabled` 只表示保存过的选择:层被跳过时
528
+ * 两项仍为真,只在 `error` 与 `rows[].entryId` 上体现,所以两者都要看。
529
+ *
530
+ * @param manager - the plugin manager.
531
+ * @param result - the install result that claimed success.
532
+ * @throws when the bundle is missing, unreadable, not loaded, or disabled.
533
+ */
534
+ async function verifyInstalled(manager, result) {
535
+ let listed
536
+ try {
537
+ listed = await manager.listBundles()
538
+ } catch (error) {
539
+ throw managerError(result, undefined, `;安装后无法读取插件列表,未能确认是否生效(${messageOf(error)})`)
540
+ }
541
+ const after = listed?.find?.((item) => item.name === PACKAGE_NAME)
542
+ if (after === undefined || after.installed === false) {
543
+ throw managerError(result, undefined, ';新版本没有注册为已启用的插件,请检查「插件」页')
544
+ }
545
+ if (after.availability === 'missing') throw managerError(result, undefined, ';新版本的文件不可读,请检查「插件」页')
546
+ if (after.error !== undefined && after.error !== null) {
547
+ const reason = after.error.code ?? after.error.diagnostic ?? '未知原因'
548
+ throw managerError(result, undefined, `;新版本没有被加载(${reason}),请检查「插件」页`)
549
+ }
550
+ if (after.enabled === false) throw managerError(result, undefined, ';新版本没有启用,请检查「插件」页')
551
+ const rows = Array.isArray(after.rows) ? after.rows : []
552
+ if (rows.length > 0 && rows.every((row) => row.entryId === undefined)) {
553
+ throw managerError(result, undefined, ';新版本的插件行没有生效,请检查「插件」页')
554
+ }
555
+ }
556
+
557
+ /**
558
+ * 安装新版,并报告管理器是否已经将其激活。
559
+ * @param ctx - 带官方管理器和可选 HMR 的插件上下文。
560
+ * @param before - 本次更新前的 {@link checkUpdate} 结果。
561
+ */
562
+ async function applyUpdate(ctx, before) {
563
+ const install = locateInstall()
564
+ if (install.kind === 'git') {
565
+ await releaseHostProxyPolicy()
566
+ releaseLocalEgress()
567
+ const { stdout } = await execFileAsync('git', ['pull', '--ff-only'], { cwd: install.dir, timeout: 60000, env: directChildEnv() })
568
+ return { updated: true, installed: packageVersion(), application: 'restart-required', restartReason: 'module-comparison', detail: stdout.trim() }
569
+ }
570
+ if (install.kind !== 'profile') throw new Error('找不到安装位置,请在「插件」页重新安装')
571
+ return await updateProfile(ctx, install, before)
572
+ }
573
+
574
+ /* --------------------------------------------------------------------- icon */
575
+
576
+ let iconCache = null
577
+ function iconBytes() {
578
+ if (iconCache === null) {
579
+ try {
580
+ iconCache = readFileSync(path.join(PLUGIN_DIR, 'icon.png'))
581
+ } catch {
582
+ iconCache = Buffer.alloc(0)
583
+ }
584
+ }
585
+ return iconCache
586
+ }
587
+
588
+ /* -------------------------------------------------------------------- apply */
589
+
590
+ /**
591
+ * Register the main row.
592
+ * @param ctx - plugin context.
593
+ */
594
+ export function apply(ctx) {
595
+ let restartQueued = false
596
+
597
+ /** Everything except the icon, behind the connection guard and one error boundary. */
598
+ const guarded = guardRoute(ctx, async (req, res) => {
599
+ const url = new URL(String(req.url), 'http://localhost')
600
+ const action = url.pathname.slice(API_PATH.length).replace(/^\/+|\/+$/g, '')
601
+
602
+ if ((action === '' || action === 'overview') && req.method === 'GET') {
603
+ sendJson(res, 200, {
604
+ ok: true,
605
+ overview: {
606
+ version: RUNNING_VERSION,
607
+ pid: process.pid,
608
+ bootId: BOOT_ID,
609
+ hostname: hostname(),
610
+ at: new Date().toISOString(),
611
+ components: mountedComponents(ctx),
612
+ },
613
+ })
614
+ return
615
+ }
616
+ if (action === 'update' && req.method === 'GET') {
617
+ sendJson(res, 200, { ok: true, update: await checkUpdate() })
618
+ return
619
+ }
620
+ if (action === 'update' && req.method === 'POST') {
621
+ const body = await readJsonBody(req).catch(() => ({}))
622
+ // The lock is taken before the first await, so two clicks cannot both
623
+ // pass a `if (updating)` check and then interleave their installs.
624
+ const result = await runExclusive('更新插件', async () => {
625
+ // 另一个 Host 进程可能正对着同一个 profile 安装;进程内锁管不到它。
626
+ const release = acquireUpdateLock(resolveDshHome())
627
+ try {
628
+ const before = await checkUpdate()
629
+ if (!before.available) return { ok: true, updated: false, update: before }
630
+ const applied = await applyUpdate(ctx, before)
631
+ const pendingRestart = applied.application === 'restart-required'
632
+ // 文件变化会先重载客户端,所以必须重启时只能由 Host 在响应后安排;
633
+ // 已经热应用的新版不能再重启一次。
634
+ let restarted = false
635
+ if (body.restart === true && pendingRestart && process.platform !== 'win32') {
636
+ scheduleRestart(planRestart({ mode: 'auto' }), { delayMs: 900, reason: 'yukari plugin update' })
637
+ restarted = true
638
+ }
639
+ return {
640
+ ok: true,
641
+ ...applied,
642
+ restarted,
643
+ update: {
644
+ ...before,
645
+ current: pendingRestart ? before.current : applied.installed,
646
+ installed: applied.installed,
647
+ currentCommit: pendingRestart ? before.currentCommit : before.latestCommit,
648
+ available: false,
649
+ pendingRestart,
650
+ restartSupported: process.platform !== 'win32',
651
+ },
652
+ }
653
+ } finally {
654
+ release()
655
+ }
656
+ })
657
+ sendJson(res, 200, result)
658
+ return
659
+ }
660
+ if (action === 'restart' && req.method === 'POST') {
661
+ if (process.platform === 'win32') throw appError('Windows 客户端不支持从面板重启 dsh', 'runtime-restart-unsupported')
662
+ if (restartQueued) throw appError('重启已经在队列里', 'restart-queued')
663
+ // Restarting mid-install would leave a half-written global prefix.
664
+ const busy = busyLabel()
665
+ if (busy !== null) {
666
+ const error = new Error(`正在${busy},请等待完成后再试`)
667
+ error.status = 409
668
+ throw error
669
+ }
670
+ const plan = planRestart({ mode: 'auto' })
671
+ const ack = scheduleRestart(plan, { delayMs: 800, reason: 'yukari panel' })
672
+ restartQueued = true
673
+ sendJson(res, 202, { ok: true, ...ack })
674
+ return
675
+ }
676
+ sendJson(res, 404, { ok: false, error: `unknown action "${action}"` })
677
+ })
678
+
679
+ ctx.effect(
680
+ () =>
681
+ ctx.webServer.register({
682
+ kind: 'prefix',
683
+ path: API_PATH,
684
+ handler: async (req, res) => {
685
+ const url = new URL(String(req.url), 'http://localhost')
686
+ const action = url.pathname.slice(API_PATH.length).replace(/^\/+|\/+$/g, '')
687
+
688
+ // The icon is fetched by <img> and has to answer without the guard.
689
+ if (action === 'icon' && req.method === 'GET') {
690
+ const bytes = iconBytes()
691
+ res.statusCode = bytes.length === 0 ? 404 : 200
692
+ res.setHeader('content-type', 'image/png')
693
+ res.setHeader('cache-control', 'public, max-age=86400')
694
+ res.end(bytes)
695
+ return
696
+ }
697
+ return guarded(req, res)
698
+ },
699
+ }),
700
+ `yukari: ${API_PATH}/*`,
701
+ )
702
+ }