dsh-desktop-statusbar 3.0.0 → 3.0.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.
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/docs/statusbar.en.png +0 -0
- package/docs/statusbar.png +0 -0
- package/lib/client.js +498 -31
- package/lib/exchange-rate.js +199 -0
- package/lib/index.js +252 -31
- package/lib/self-update.js +338 -35
- package/package.json +1 -1
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 每日汇率:北京时间每天 9:00 之后拉一次「1 USD = ? CNY」,缓存到本地。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:余额色条要把两种货币的余额折成同一口径算比例,底栏「本轮 / 总计」
|
|
5
|
+
* 也要一个合并数字。以前这个汇率是**从内置价格表反算出来的常量**(client.js 的
|
|
6
|
+
* REFERENCE_RATE),它只反映写代码那天的行情,之后一直不变。
|
|
7
|
+
*
|
|
8
|
+
* 为什么不用银联:银联没有面向公众的免费 API,只有网页查询页,抓页面随时会坏。
|
|
9
|
+
* 用户确认改用公开汇率源(open.er-api.com),它每天 UTC 00:00 左右更新一次,
|
|
10
|
+
* 换算成北京时间约 08:00,正好在 9:00 之前落地。
|
|
11
|
+
*
|
|
12
|
+
* 为什么失败要静默:汇率是显示用的辅助数据,拉不到不该打扰用户。
|
|
13
|
+
* 拉不到就用上次成功的那一份;从没成功过就返回 null,调用方退回内置常量。
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
16
|
+
import { homedir } from 'node:os'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
|
|
19
|
+
/** 汇率接口:基准货币是 CNY,返回里 rates.USD 是「1 CNY = ? USD」。 */
|
|
20
|
+
const RATE_URL = 'https://open.er-api.com/v6/latest/CNY'
|
|
21
|
+
/** 缓存文件路径(与台账同目录,都在 dsh-status-bar 下)。 */
|
|
22
|
+
const CACHE_FILE_NAME = 'exchange-rate.json'
|
|
23
|
+
/** 拉取超时:汇率是锦上添花的东西,不该拖住任何主流程。 */
|
|
24
|
+
const FETCH_TIMEOUT_MS = 8000
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 缓存目录:与 usage-ledger.json 同一个 dsh-status-bar 目录。
|
|
28
|
+
*
|
|
29
|
+
* **必须跟着 `DSH_HOME` 走,不能用 `homedir()`**:台账那边一直读 `DSH_HOME`
|
|
30
|
+
* (见 index.js 的 ledgerPath),测试把它指到临时目录。早先这里硬编码 `homedir()`,
|
|
31
|
+
* 结果测试读到的是真实用户主目录里的缓存 —— 既让测试之间互相污染,也让
|
|
32
|
+
* 「预置一份缓存让测试不抓汇率」这种隔离手段完全失效(实测踩过)。
|
|
33
|
+
*/
|
|
34
|
+
function cacheDir() {
|
|
35
|
+
const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== null && String(process.env.DSH_HOME).length > 0
|
|
36
|
+
? String(process.env.DSH_HOME)
|
|
37
|
+
: join(homedir(), '.dsh')
|
|
38
|
+
return join(home, 'dsh-status-bar')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 缓存文件的绝对路径。 */
|
|
42
|
+
export function cacheFilePath() {
|
|
43
|
+
return join(cacheDir(), CACHE_FILE_NAME)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 读缓存的汇率。
|
|
48
|
+
*
|
|
49
|
+
* 返回 `{ rate, fetchedAt, source }`;文件不存在 / 坏数据 / rate 不合理都返回 null。
|
|
50
|
+
* `rate` 的含义固定是「1 USD = rate CNY」,与 client.js 里 REFERENCE_RATE 同向,
|
|
51
|
+
* 调用方可以直接替换,不需要再做方向换算。
|
|
52
|
+
*
|
|
53
|
+
* @returns {{rate: number, fetchedAt: number, source: string}|null}
|
|
54
|
+
*/
|
|
55
|
+
export function readCachedRate() {
|
|
56
|
+
try {
|
|
57
|
+
const file = cacheFilePath()
|
|
58
|
+
if (existsSync(file) !== true) return null
|
|
59
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
60
|
+
if (parsed === null || typeof parsed !== 'object') return null
|
|
61
|
+
const rate = Number(parsed.rate)
|
|
62
|
+
if (Number.isFinite(rate) !== true || rate <= 0) return null
|
|
63
|
+
/* 合理性下限:人民币兑美元历史上没到过 1:1 以下,超出这个范围说明数据坏了,
|
|
64
|
+
宁可退回内置常量也不要拿一个荒谬的汇率去折算金额。 */
|
|
65
|
+
if (rate < 3 || rate > 20) return null
|
|
66
|
+
return {
|
|
67
|
+
rate: rate,
|
|
68
|
+
fetchedAt: Number.isFinite(Number(parsed.fetchedAt)) ? Number(parsed.fetchedAt) : 0,
|
|
69
|
+
source: typeof parsed.source === 'string' ? parsed.source : 'unknown',
|
|
70
|
+
}
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 把接口返回换算成「1 USD = ? CNY」。
|
|
78
|
+
*
|
|
79
|
+
* 接口给的是 `base_code: CNY` + `rates.USD`,即「1 CNY = X USD」,
|
|
80
|
+
* 所以取倒数。字段缺失 / 非数字 / 不合理都返回 null。
|
|
81
|
+
*
|
|
82
|
+
* @param {unknown} payload
|
|
83
|
+
* @returns {number|null}
|
|
84
|
+
*/
|
|
85
|
+
export function rateFromPayload(payload) {
|
|
86
|
+
if (payload === null || typeof payload !== 'object') return null
|
|
87
|
+
const body = payload
|
|
88
|
+
if (body.result !== undefined && body.result !== 'success') return null
|
|
89
|
+
if (body.base_code !== undefined && body.base_code !== 'CNY') return null
|
|
90
|
+
const rates = body.rates
|
|
91
|
+
if (rates === null || typeof rates !== 'object') return null
|
|
92
|
+
const usdPerCny = Number(rates.USD)
|
|
93
|
+
if (Number.isFinite(usdPerCny) !== true || usdPerCny <= 0) return null
|
|
94
|
+
const cnyPerUsd = 1 / usdPerCny
|
|
95
|
+
if (cnyPerUsd < 3 || cnyPerUsd > 20) return null
|
|
96
|
+
/* 保留 4 位:再多没有意义,还会让缓存文件里的数字看起来可疑。 */
|
|
97
|
+
return Math.round(cnyPerUsd * 10000) / 10000
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 拉一次汇率并写缓存。**任何异常都静默**,只以结构化结果返回。
|
|
102
|
+
*
|
|
103
|
+
* @param {{logger?: Function, fetchImpl?: Function, now?: number}} [options]
|
|
104
|
+
* @returns {Promise<{ok: boolean, rate: number|null, fetchedAt: number, reason: string|null}>}
|
|
105
|
+
*/
|
|
106
|
+
export async function fetchAndCacheRate(options) {
|
|
107
|
+
const opts = options === null || typeof options !== 'object' ? {} : options
|
|
108
|
+
const log = typeof opts.logger === 'function' ? opts.logger : () => {}
|
|
109
|
+
const now = Number.isFinite(Number(opts.now)) ? Number(opts.now) : Date.now()
|
|
110
|
+
const doFetch = typeof opts.fetchImpl === 'function' ? opts.fetchImpl : fetch
|
|
111
|
+
try {
|
|
112
|
+
const response = await doFetch(RATE_URL, {
|
|
113
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
114
|
+
headers: { accept: 'application/json' },
|
|
115
|
+
})
|
|
116
|
+
if (response === null || typeof response !== 'object' || response.ok !== true) {
|
|
117
|
+
return { ok: false, rate: null, fetchedAt: now, reason: 'http-' + String(response === null || response === undefined ? 'unknown' : response.status) }
|
|
118
|
+
}
|
|
119
|
+
const payload = await response.json()
|
|
120
|
+
const rate = rateFromPayload(payload)
|
|
121
|
+
if (rate === null) {
|
|
122
|
+
return { ok: false, rate: null, fetchedAt: now, reason: 'bad-payload' }
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const dir = cacheDir()
|
|
126
|
+
if (existsSync(dir) !== true) mkdirSync(dir, { recursive: true })
|
|
127
|
+
writeFileSync(cacheFilePath(), JSON.stringify({
|
|
128
|
+
rate: rate,
|
|
129
|
+
fetchedAt: now,
|
|
130
|
+
source: 'open.er-api.com',
|
|
131
|
+
}), 'utf8')
|
|
132
|
+
} catch (error) {
|
|
133
|
+
/* 写不进缓存不算失败:这一拍拿到了汇率,调用方照样能用 */
|
|
134
|
+
log('exchange-rate: 缓存写入失败 ' + String(error === null || error === undefined ? 'unknown' : error.message))
|
|
135
|
+
}
|
|
136
|
+
log('exchange-rate: 1 USD = ' + String(rate) + ' CNY')
|
|
137
|
+
return { ok: true, rate: rate, fetchedAt: now, reason: null }
|
|
138
|
+
} catch (error) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
rate: null,
|
|
142
|
+
fetchedAt: now,
|
|
143
|
+
reason: 'request-failed',
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 今天(本地时区)09:00 的时间戳。
|
|
150
|
+
*
|
|
151
|
+
* 用**本地时区**而不是硬编码 UTC+8:用户机器如果不在东八区,按本地 9 点拉也是对的
|
|
152
|
+
* —— 它要的是「今天开始上班之后拿一份当天的汇率」,不是「北京时间 9 点整」。
|
|
153
|
+
*
|
|
154
|
+
* @param {number} now 毫秒时间戳
|
|
155
|
+
* @returns {number}
|
|
156
|
+
*/
|
|
157
|
+
export function nineAmOf(now) {
|
|
158
|
+
const date = new Date(Number.isFinite(Number(now)) ? Number(now) : Date.now())
|
|
159
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 9, 0, 0, 0).getTime()
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 此刻该不该去拉汇率。
|
|
164
|
+
*
|
|
165
|
+
* 判据三条,缺一不可:
|
|
166
|
+
* 1. **今天 9:00 之前一律不拉** —— 接口每天 UTC 00:00 左右才更新(北京约 08:00),
|
|
167
|
+
* 9 点前拉到的还是上一日的价。早先漏了这一条,早上 8 点打开就会白拉一次。
|
|
168
|
+
* 2. 缓存为空 ⇒ 拉。
|
|
169
|
+
* 3. 缓存的拉取时间早于**今天 9:00** ⇒ 拉(说明今天还没拉过)。
|
|
170
|
+
*
|
|
171
|
+
* 于是「一天最多拉一次」是**由缓存时间戳保证的**:9 点后第一拍拉完就写缓存,
|
|
172
|
+
* 之后无论被调用多少次(余额路由每 60 秒问一次、用户反复重启 DSH)都会命中第 3 条为假,
|
|
173
|
+
* 一次都不会再发请求。
|
|
174
|
+
*
|
|
175
|
+
* @param {{rate: number, fetchedAt: number}|null} cached
|
|
176
|
+
* @param {number} now
|
|
177
|
+
* @returns {boolean}
|
|
178
|
+
*/
|
|
179
|
+
export function shouldRefresh(cached, now) {
|
|
180
|
+
const today9 = nineAmOf(now)
|
|
181
|
+
/* 9 点之前:今天这一份还没到发布时间,一次都不拉(有缓存就继续用昨天的)。 */
|
|
182
|
+
if (Number(now) < today9) return false
|
|
183
|
+
if (cached === null || cached === undefined) return true
|
|
184
|
+
const fetchedAt = Number(cached.fetchedAt)
|
|
185
|
+
if (Number.isFinite(fetchedAt) !== true) return true
|
|
186
|
+
return fetchedAt < today9
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 当前该用的汇率(「1 USD = ? CNY」)。
|
|
191
|
+
*
|
|
192
|
+
* 有缓存用缓存,没缓存返回 null —— 调用方据此退回 client.js 的 REFERENCE_RATE。
|
|
193
|
+
*
|
|
194
|
+
* @returns {number|null}
|
|
195
|
+
*/
|
|
196
|
+
export function currentRate() {
|
|
197
|
+
const cached = readCachedRate()
|
|
198
|
+
return cached === null ? null : cached.rate
|
|
199
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -45,6 +45,7 @@ import { z } from 'zod'
|
|
|
45
45
|
import { adapterFor, adaptersFor, pluginRoutesIn } from './balance-api.js'
|
|
46
46
|
import { holidayHtmlToText, parseHolidayNotice } from './holiday.js'
|
|
47
47
|
import { isUpdating, lastUpdateResult, resolveSelfDir, selfUpdateOnce } from './self-update.js'
|
|
48
|
+
import { currentRate as currentExchangeRate, fetchAndCacheRate, nineAmOf, readCachedRate, shouldRefresh } from './exchange-rate.js'
|
|
48
49
|
import { appendFileSync, closeSync, copyFileSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
49
50
|
/* 异步读盘用:扫描热点上按文件 `fs.promises.readFile`,读 8 MB 日志的这 5 ms 也别占主线程。 */
|
|
50
51
|
import { promises as fsPromises } from 'node:fs'
|
|
@@ -4550,6 +4551,19 @@ function addDayCost(day, model, amount) {
|
|
|
4550
4551
|
/* 只按自有属性累加:模型名不会当币种键,但保持与 addUnpriced 同一套防御习惯 */
|
|
4551
4552
|
const hasOwn = Object.prototype.hasOwnProperty.call(book, code)
|
|
4552
4553
|
book[code] = (hasOwn === true ? book[code] : 0) + amount
|
|
4554
|
+
/* 顺手记下"这一天的钱是按什么汇率折的"(只记非 CNY 币种:CNY 折 CNY 恒为 1)。
|
|
4555
|
+
为什么要有它:底栏「本轮 / 总计」是一个**合并数字**,得把美元折成人民币。
|
|
4556
|
+
以前那个汇率是写死的常量,于是历史金额会随常量改动而整体漂移。
|
|
4557
|
+
记下来之后,每天用自己的汇率折算,历史数字就固定了。
|
|
4558
|
+
**不覆盖已有的**:同一天可能有多次写入,保留当天第一次记下的那个汇率。 */
|
|
4559
|
+
if (code !== 'CNY') {
|
|
4560
|
+
const current = currentExchangeRate()
|
|
4561
|
+
if (current !== null) {
|
|
4562
|
+
if (day.rateAt === undefined || day.rateAt === null || typeof day.rateAt !== 'object') day.rateAt = {}
|
|
4563
|
+
const seen = Object.prototype.hasOwnProperty.call(day.rateAt, code)
|
|
4564
|
+
if (seen !== true) day.rateAt[code] = current
|
|
4565
|
+
}
|
|
4566
|
+
}
|
|
4553
4567
|
}
|
|
4554
4568
|
|
|
4555
4569
|
/**
|
|
@@ -5062,6 +5076,165 @@ function appendTipDiag(body) {
|
|
|
5062
5076
|
}
|
|
5063
5077
|
}
|
|
5064
5078
|
|
|
5079
|
+
/**
|
|
5080
|
+
* 从 pnpm 的原始输出里挑出「有意义的错误行」。
|
|
5081
|
+
*
|
|
5082
|
+
* 为什么不整段贴:pnpm 的 append-only 输出里绝大多数是进度行(`Progress: resolved 12,
|
|
5083
|
+
* reused 0, downloaded 0`)和 `Packages: +3` 这类统计,真正的错误通常只有一两行,
|
|
5084
|
+
* 混在一大段里反而看不清。这里只认三类信号:
|
|
5085
|
+
* · pnpm 的错误码:`ERR_PNPM_*` / `ERR_SQLITE_ERROR` / `ERR_INVALID_*`(统一前缀 ERR_)
|
|
5086
|
+
* · Node 的系统错误码:行首或空白后的 `E` + 大写字母组合 + 冒号(ENOSPC / EPERM: …)
|
|
5087
|
+
* · 通用异常:`Error:` / `ELIFECYCLE`(脚本失败)
|
|
5088
|
+
*
|
|
5089
|
+
* 输不出任何一条时退回「输出的最后一行非空内容」—— 那时至少给出一句人话可读的原文,
|
|
5090
|
+
* 比只写「安装失败」强。**这个保底只给 stderr 用**:stdout 里最后一行多半是
|
|
5091
|
+
* `Packages: +3` 这类统计,拿它当"错误行"反而误导。
|
|
5092
|
+
*
|
|
5093
|
+
* @param {string} text stdout 或 stderr
|
|
5094
|
+
* @param {number} limit 最多取几条
|
|
5095
|
+
* @param {boolean} [allowFallback] 没有匹配行时是否退回最后一行(默认 true)
|
|
5096
|
+
* @returns {string[]}
|
|
5097
|
+
*/
|
|
5098
|
+
function pickPnpmErrorLines(text, limit, allowFallback) {
|
|
5099
|
+
const raw = String(text === null || text === undefined ? '' : text)
|
|
5100
|
+
const lines = raw.split(/\r?\n/).map((one) => one.trim()).filter((one) => one.length > 0)
|
|
5101
|
+
const hit = lines.filter((one) => /ERR_[A-Z0-9_]+|\bE[A-Z]{2,}\b|Error:|ELIFECYCLE/.test(one))
|
|
5102
|
+
const allowLast = allowFallback !== false
|
|
5103
|
+
const picked = hit.length > 0 ? hit : (allowLast === true && lines.length > 0 ? [lines[lines.length - 1]] : [])
|
|
5104
|
+
/* 去重(stdout 与 stderr 里常出现同一行)+ 截断,最多 limit 条 */
|
|
5105
|
+
const seen = new Set()
|
|
5106
|
+
const out = []
|
|
5107
|
+
for (const line of picked) {
|
|
5108
|
+
const clean = line.length > 300 ? line.slice(0, 300) + '…' : line
|
|
5109
|
+
if (seen.has(clean) === true) continue
|
|
5110
|
+
seen.add(clean)
|
|
5111
|
+
out.push(clean)
|
|
5112
|
+
if (out.length >= limit) break
|
|
5113
|
+
}
|
|
5114
|
+
return out
|
|
5115
|
+
}
|
|
5116
|
+
|
|
5117
|
+
/**
|
|
5118
|
+
* 把宿主自己那次安装失败(self-update.js 的 `result.failureReport`)写成一句可读摘要。
|
|
5119
|
+
*
|
|
5120
|
+
* 与客户端失败不同,这里的字段**宿主全都知道**(它自己跑的 pnpm),所以能给出
|
|
5121
|
+
* 「哪个阶段、退出码多少、pnpm 原话是什么、有没有回滚」这四件对排查最有用的事实。
|
|
5122
|
+
* 用户拿着这句话就能直接搜错误码,不用先翻一整屏日志。
|
|
5123
|
+
*
|
|
5124
|
+
* @param {object} body failureReport
|
|
5125
|
+
* @returns {string}
|
|
5126
|
+
*/
|
|
5127
|
+
function describeHostInstallFailure(body) {
|
|
5128
|
+
const src = body !== null && body !== undefined && typeof body === 'object' ? body : {}
|
|
5129
|
+
const repair = src.mode === 'repair'
|
|
5130
|
+
const head = repair ? '修复安装阶段失败' : '安装阶段失败'
|
|
5131
|
+
const reasons = []
|
|
5132
|
+
if (typeof src.exitCode === 'number' && Number.isFinite(src.exitCode)) reasons.push('exit ' + String(src.exitCode))
|
|
5133
|
+
else if (src.timedOut === true) reasons.push('超时')
|
|
5134
|
+
const reason = typeof src.reason === 'string' && src.reason.length > 0 ? src.reason : null
|
|
5135
|
+
if (reason !== null) reasons.push(reason)
|
|
5136
|
+
/* pnpm 的真实错误行优先从 stderr 取,再从 stdout 补(有的版本把错误写在 stdout);
|
|
5137
|
+
stdout 不做"取最后一行"的保底 —— 那一行通常是 `Packages: +3` 这种统计。 */
|
|
5138
|
+
const errLines = pickPnpmErrorLines(src.stderr, 2, true).concat(pickPnpmErrorLines(src.stdout, 2, false))
|
|
5139
|
+
const unique = []
|
|
5140
|
+
for (const line of errLines) {
|
|
5141
|
+
if (unique.indexOf(line) < 0) unique.push(line)
|
|
5142
|
+
if (unique.length >= 3) break
|
|
5143
|
+
}
|
|
5144
|
+
const where = reasons.length > 0 ? '(' + reasons.join(',') + ')' : ''
|
|
5145
|
+
const detail = unique.length > 0 ? ':' + unique.join(' | ') : ''
|
|
5146
|
+
const rollback = src.rolledBack === true
|
|
5147
|
+
? '已回滚配置,环境未被改动。'
|
|
5148
|
+
: '未能回滚配置,环境可能仍处于中间状态。'
|
|
5149
|
+
return head + where + detail + ';' + rollback
|
|
5150
|
+
}
|
|
5151
|
+
|
|
5152
|
+
/**
|
|
5153
|
+
* 最近一条更新失败记录(客户端上报或宿主自更新失败),给状态接口读。
|
|
5154
|
+
*
|
|
5155
|
+
* 为什么要留最近一条而不是只写日志:日志是给开发者 tail 的,用户手上没有;
|
|
5156
|
+
* 而 GET /api/self-update 要把「失败之后能做什么」告诉界面时,需要这份结构化数据
|
|
5157
|
+
* (尤其是 `stage` 与 `rolledBack`:是宿主装挂了并已回滚,还是浏览器那边请求
|
|
5158
|
+
* 没发出去/回包解不开)。只留一条足够 —— 用户关心的是"刚刚这一次为什么失败"。
|
|
5159
|
+
*/
|
|
5160
|
+
let lastUpdateFailure = null
|
|
5161
|
+
|
|
5162
|
+
/**
|
|
5163
|
+
* 更新失败的统一落地点:写一条日志 + 记下最近一条。
|
|
5164
|
+
*
|
|
5165
|
+
* 两个来源共用它,保证「日志里有什么」与「状态接口里有什么」永远同源:
|
|
5166
|
+
* 1. 客户端 POST /api/update-failure(浏览器侧失败:fetch 被拦、回包解不开、HTTP 4xx);
|
|
5167
|
+
* 2. 宿主自己跑 pnpm 失败时内部直接调用(body = self-update.js 的 failureReport)。
|
|
5168
|
+
*
|
|
5169
|
+
* 为什么宿主那一侧是**直接函数调用**而不是 HTTP 回环到自己:
|
|
5170
|
+
* · 这个路由的全部效果就是「写日志 + 存一条」,纯进程内状态,没有任何需要走网络的理由;
|
|
5171
|
+
* · 回环会多一次 socket 往返,还要依赖 webServer 端口/监听状态,失败时反而会
|
|
5172
|
+
* 把一个诊断动作变成新的失败点(还得再兜一层 try)。
|
|
5173
|
+
*
|
|
5174
|
+
* @param {object} ctx 插件上下文(拿 logger)
|
|
5175
|
+
* @param {object|null} body 上报体 / failureReport
|
|
5176
|
+
*/
|
|
5177
|
+
function recordUpdateFailure(ctx, body) {
|
|
5178
|
+
const src = body !== null && body !== undefined && typeof body === 'object' ? body : {}
|
|
5179
|
+
/* 体量上限:stdout/stderr 各 64KB(见 self-update.js 的 OUTPUT_LIMIT),
|
|
5180
|
+
这里整体再压一层,避免把一整份输出塞进内存里的"最近一条"。
|
|
5181
|
+
|
|
5182
|
+
**原文也要留**:summary 是提炼过的中文摘要,用户排查时最需要的恰恰是 pnpm 的原话
|
|
5183
|
+
(哪一步、哪个包、什么错误码)。以前只留 summary,界面上就只剩「更新失败」四个字。
|
|
5184
|
+
尾部优先 —— pnpm 的失败结论总在最后几行。 */
|
|
5185
|
+
const tail = (text, limit) => {
|
|
5186
|
+
if (typeof text !== 'string' || text.length === 0) return ''
|
|
5187
|
+
return text.length <= limit ? text : text.slice(-limit)
|
|
5188
|
+
}
|
|
5189
|
+
lastUpdateFailure = {
|
|
5190
|
+
stage: typeof src.stage === 'string' ? src.stage.slice(0, 60) : 'unknown',
|
|
5191
|
+
mode: src.mode === 'repair' ? 'repair' : 'update',
|
|
5192
|
+
reason: typeof src.reason === 'string' ? src.reason.slice(0, 120) : null,
|
|
5193
|
+
rolledBack: src.rolledBack === true,
|
|
5194
|
+
at: Date.now(),
|
|
5195
|
+
summary: describeClientUpdateFailure(src),
|
|
5196
|
+
/* 界面直接把这两段原样摊在按钮下方(不滚动、不展开),所以这里就是"给人看的那份"。 */
|
|
5197
|
+
stdout: tail(src.stdout, UPDATE_FAILURE_OUTPUT_LIMIT),
|
|
5198
|
+
stderr: tail(src.stderr, UPDATE_FAILURE_OUTPUT_LIMIT),
|
|
5199
|
+
exitCode: typeof src.exitCode === 'number' ? src.exitCode : null,
|
|
5200
|
+
}
|
|
5201
|
+
logHost(ctx, 'update: 失败 ' + lastUpdateFailure.summary)
|
|
5202
|
+
}
|
|
5203
|
+
|
|
5204
|
+
/** 最近一条更新失败记录里保留的原始输出长度(尾部)。界面那块也是按这个量级展示的。 */
|
|
5205
|
+
const UPDATE_FAILURE_OUTPUT_LIMIT = 12000
|
|
5206
|
+
|
|
5207
|
+
/** 最近一条更新失败记录;没失败过就是 null。 */
|
|
5208
|
+
function lastUpdateFailureRecord() {
|
|
5209
|
+
return lastUpdateFailure
|
|
5210
|
+
}
|
|
5211
|
+
|
|
5212
|
+
/**
|
|
5213
|
+
* 日志里打印更新结果时用的紧凑版。
|
|
5214
|
+
*
|
|
5215
|
+
* 为什么不能直接 `JSON.stringify(value)`:`failureReport.stdout/stderr` 是 pnpm 的
|
|
5216
|
+
* 原始输出(各上限 64000 字符),一次失败会把几十 KB 灌进日志,同一次失败的
|
|
5217
|
+
* 可读摘要反而被淹掉。日志里只留结论字段,原文只在状态接口/诊断面按需取。
|
|
5218
|
+
*
|
|
5219
|
+
* @param {object} value selfUpdateOnce 的返回值
|
|
5220
|
+
* @returns {object}
|
|
5221
|
+
*/
|
|
5222
|
+
function compactUpdateResult(value) {
|
|
5223
|
+
const src = value !== null && value !== undefined && typeof value === 'object' ? value : {}
|
|
5224
|
+
const out = {
|
|
5225
|
+
ok: src.ok === true,
|
|
5226
|
+
mode: src.mode === 'repair' ? 'repair' : 'update',
|
|
5227
|
+
reason: src.reason === undefined ? null : src.reason,
|
|
5228
|
+
from: src.from === undefined ? null : src.from,
|
|
5229
|
+
to: src.to === undefined ? null : src.to,
|
|
5230
|
+
rolledBack: src.rolledBack === true,
|
|
5231
|
+
}
|
|
5232
|
+
if (src.failureReport !== undefined && src.failureReport !== null) {
|
|
5233
|
+
out.failureReport = '[已记入 update-failure] ' + describeClientUpdateFailure(src.failureReport)
|
|
5234
|
+
}
|
|
5235
|
+
return out
|
|
5236
|
+
}
|
|
5237
|
+
|
|
5065
5238
|
/**
|
|
5066
5239
|
* 把客户端上报的「更新失败」描述成一条能直接拿去问 AI 的日志文本。
|
|
5067
5240
|
*
|
|
@@ -5071,11 +5244,18 @@ function appendTipDiag(body) {
|
|
|
5071
5244
|
*
|
|
5072
5245
|
* 只取有限长度的字符串,避免恶意/异常的超长 body 把日志撑爆。
|
|
5073
5246
|
*
|
|
5074
|
-
*
|
|
5247
|
+
* `stage === 'host-install'` 是另一类:那时 body 就是 self-update.js 产出的
|
|
5248
|
+
* `failureReport`(宿主自己跑 pnpm 失败),字段完全不同(exitCode / stdout /
|
|
5249
|
+
* stderr / command / rolledBack),要按它自己的口径解读,不能套客户端那套。
|
|
5250
|
+
*
|
|
5251
|
+
* @param {object|null} body 客户端 POST 上来的 JSON,或宿主内部的 failureReport
|
|
5075
5252
|
* @returns {string}
|
|
5076
5253
|
*/
|
|
5077
5254
|
function describeClientUpdateFailure(body) {
|
|
5078
5255
|
const src = body !== null && body !== undefined && typeof body === 'object' ? body : {}
|
|
5256
|
+
/* 宿主安装失败优先:它有准确语义(退出码 + pnpm 原话 + 回滚结果),
|
|
5257
|
+
比客户端泛泛的「失败」信息量大得多,别再拼一串 target/current 冲淡它。 */
|
|
5258
|
+
if (src.stage === 'host-install') return describeHostInstallFailure(src)
|
|
5079
5259
|
const text = (value, max) => {
|
|
5080
5260
|
if (value === null || value === undefined) return null
|
|
5081
5261
|
const raw = typeof value === 'string' ? value : String(value)
|
|
@@ -5466,20 +5646,29 @@ async function handleApi(req, res, ctx) {
|
|
|
5466
5646
|
&& compareVersions(latestVersion.latest, current) > 0,
|
|
5467
5647
|
checkedAt: latestVersion.checkedAt,
|
|
5468
5648
|
error: latestVersion.error,
|
|
5649
|
+
/* 最近一次失败的原文一并带回去:界面要把它摊在更新按钮下方。
|
|
5650
|
+
走这个接口而不是单独加一个路由 —— 客户端每次刷新本来就会问它一次,
|
|
5651
|
+
多一个字段比多一次请求划算,也不会出现「自检回来了、报错还没回来」的半态。 */
|
|
5652
|
+
lastFailure: lastUpdateFailureRecord(),
|
|
5469
5653
|
})
|
|
5470
5654
|
return
|
|
5471
5655
|
}
|
|
5472
5656
|
if (url.pathname === '/dsh-desktop-statusbar/api/self-update') {
|
|
5473
5657
|
/* 一键更新:由本插件自己完成,不依赖「插件管理器」这个别的插件,也不走
|
|
5474
5658
|
pnpm 的 24 小时发布年龄策略(做法见 self-update.js 顶部说明)。
|
|
5475
|
-
GET = 问当前状态(界面挂在更新中途刷新时能接上);POST = 发起一次更新。
|
|
5659
|
+
GET = 问当前状态(界面挂在更新中途刷新时能接上);POST = 发起一次更新。
|
|
5660
|
+
`?mode=repair` = 修复安装:不装新版本,只让 pnpm 按现有清单把 node_modules
|
|
5661
|
+
对齐(升级失败后 package.json / 锁文件 / 实物互相矛盾的场景)。 */
|
|
5662
|
+
const mode = url.searchParams.get('mode') === 'repair' ? 'repair' : 'update'
|
|
5476
5663
|
if (req.method !== 'POST') {
|
|
5477
5664
|
const last = lastUpdateResult()
|
|
5665
|
+
const failure = lastUpdateFailureRecord()
|
|
5478
5666
|
sendJson(res, 200, {
|
|
5479
5667
|
ok: true,
|
|
5480
5668
|
busy: isUpdating(),
|
|
5481
5669
|
last: last === null ? null : {
|
|
5482
5670
|
ok: last.ok === true,
|
|
5671
|
+
mode: last.mode === 'repair' ? 'repair' : 'update',
|
|
5483
5672
|
reason: last.reason === undefined ? null : last.reason,
|
|
5484
5673
|
from: last.from === undefined ? null : last.from,
|
|
5485
5674
|
to: last.to === undefined ? null : last.to,
|
|
@@ -5487,40 +5676,60 @@ async function handleApi(req, res, ctx) {
|
|
|
5487
5676
|
手工逐条 Test-Path,这里直接摊开。其它失败原因下是空数组。 */
|
|
5488
5677
|
tried: Array.isArray(last.tried) === true ? last.tried : [],
|
|
5489
5678
|
},
|
|
5679
|
+
/* 最近一次失败的**可读摘要**(宿主装挂了会带 pnpm 的错误行;客户端失败则带
|
|
5680
|
+
它自己报上来的 stage/detail)。界面不强制用它,排查时它是最短的一条线索。 */
|
|
5681
|
+
lastFailure: failure,
|
|
5490
5682
|
})
|
|
5491
5683
|
return
|
|
5492
5684
|
}
|
|
5493
5685
|
const body = await readJsonBody(req)
|
|
5494
|
-
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
|
|
5504
|
-
|
|
5505
|
-
|
|
5506
|
-
if (target.length === 0) {
|
|
5507
|
-
/* 客户端没带版本就自己查一次最新的 */
|
|
5508
|
-
const checked = await checkLatestVersion()
|
|
5509
|
-
latestVersion = checked
|
|
5510
|
-
if (checked.latest === null) {
|
|
5511
|
-
sendJson(res, 200, { ok: false, reason: checked.error === null ? 'no-version' : checked.error })
|
|
5686
|
+
/* repair 模式不需要目标版本:它装的是"现有清单里写的那些",所以整段版本校验跳过。 */
|
|
5687
|
+
let target = ''
|
|
5688
|
+
if (mode !== 'repair') {
|
|
5689
|
+
const raw = body === null || typeof body.version !== 'string' ? '' : body.version.trim()
|
|
5690
|
+
/* 目标版本必须是明确的三段式版本号:不接受 latest/tag/范围,避免装到别的东西。
|
|
5691
|
+
空则不传 —— host 会自己问 registry 的最新版。 */
|
|
5692
|
+
if (raw.length > 0 && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(raw) !== true) {
|
|
5693
|
+
sendJson(res, 400, { ok: false, reason: 'bad-version' })
|
|
5694
|
+
return
|
|
5695
|
+
}
|
|
5696
|
+
if (isUpdating() === true) {
|
|
5697
|
+
sendJson(res, 409, { ok: false, reason: 'busy' })
|
|
5512
5698
|
return
|
|
5513
5699
|
}
|
|
5514
|
-
target =
|
|
5700
|
+
target = raw
|
|
5701
|
+
if (target.length === 0) {
|
|
5702
|
+
/* 客户端没带版本就自己查一次最新的 */
|
|
5703
|
+
const checked = await checkLatestVersion()
|
|
5704
|
+
latestVersion = checked
|
|
5705
|
+
if (checked.latest === null) {
|
|
5706
|
+
sendJson(res, 200, { ok: false, reason: checked.error === null ? 'no-version' : checked.error })
|
|
5707
|
+
return
|
|
5708
|
+
}
|
|
5709
|
+
target = checked.latest
|
|
5710
|
+
}
|
|
5711
|
+
} else if (isUpdating() === true) {
|
|
5712
|
+
sendJson(res, 409, { ok: false, reason: 'busy' })
|
|
5713
|
+
return
|
|
5515
5714
|
}
|
|
5516
5715
|
const selfDir = resolveSelfDir()
|
|
5517
|
-
logHost(ctxRef,
|
|
5716
|
+
logHost(ctxRef, mode === 'repair'
|
|
5717
|
+
? 'update: 收到修复安装请求(mode=repair,当前目录 ' + selfDir + ')'
|
|
5718
|
+
: 'update: 收到更新请求 → ' + target + '(当前目录 ' + selfDir + ')')
|
|
5518
5719
|
const value = await selfUpdateOnce({
|
|
5519
5720
|
selfDir,
|
|
5520
5721
|
version: target,
|
|
5722
|
+
mode,
|
|
5521
5723
|
logger: (message) => logHost(ctxRef, message),
|
|
5522
5724
|
})
|
|
5523
|
-
logHost(ctxRef, 'update: 结果 ' + JSON.stringify(value))
|
|
5725
|
+
logHost(ctxRef, 'update: 结果 ' + JSON.stringify(compactUpdateResult(value)))
|
|
5726
|
+
/* M2 的收尾:失败时把结构化 failureReport 落到同一个诊断面(/api/update-failure)。
|
|
5727
|
+
这里**不走 HTTP 自己请求自己** —— 那要多一次回环、还可能被跨站防护/端口变化挡掉,
|
|
5728
|
+
而且它要做的两件事(写日志 + 记最近一条失败)本来就是本进程内的纯函数调用。
|
|
5729
|
+
下面 recordUpdateFailure 与 update-failure 路由共用同一个落地点。 */
|
|
5730
|
+
if (value.ok !== true && value.failureReport !== undefined && value.failureReport !== null) {
|
|
5731
|
+
recordUpdateFailure(ctx, value.failureReport)
|
|
5732
|
+
}
|
|
5524
5733
|
sendJson(res, 200, value)
|
|
5525
5734
|
return
|
|
5526
5735
|
}
|
|
@@ -5599,15 +5808,18 @@ async function handleApi(req, res, ctx) {
|
|
|
5599
5808
|
return
|
|
5600
5809
|
}
|
|
5601
5810
|
if (url.pathname === '/dsh-desktop-statusbar/api/update-failure') {
|
|
5602
|
-
/*
|
|
5603
|
-
`update: 结果 {...}`
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5811
|
+
/* 更新失败的上报口(诊断面)。为什么需要它:宿主自己跑 pnpm 的那次失败已经由
|
|
5812
|
+
`update: 结果 {...}` 记了,但**客户端自己**的失败(fetch 被代理拦、响应解不出来、
|
|
5813
|
+
网络断)发生在浏览器里,宿主完全不知道 —— 用户点完只看到「更新失败」,
|
|
5814
|
+
日志里查不到任何痕迹,想用 AI 排查也无从下手。
|
|
5815
|
+
这里把它补成一条**结构化记录**:既有给人看的中文摘要,也留一份最近记录
|
|
5816
|
+
给 GET /api/self-update 用(见 recordUpdateFailure)。
|
|
5817
|
+
不做状态变更、不重试安装,所以是纯诊断面。
|
|
5818
|
+
**宿主自己的 failureReport 不走这里**(同一个函数由 self-update 那条路由
|
|
5819
|
+
直接调用):回环 HTTP 只是把进程内调用包装成一次多余的 socket 往返。 */
|
|
5608
5820
|
if (req.method === 'POST') {
|
|
5609
5821
|
const body = await readJsonBody(req)
|
|
5610
|
-
|
|
5822
|
+
recordUpdateFailure(ctx, body)
|
|
5611
5823
|
}
|
|
5612
5824
|
sendJson(res, 200, { ok: true })
|
|
5613
5825
|
return
|
|
@@ -5617,6 +5829,15 @@ async function handleApi(req, res, ctx) {
|
|
|
5617
5829
|
return
|
|
5618
5830
|
}
|
|
5619
5831
|
const force = url.searchParams.get('force') === '1'
|
|
5832
|
+
/* 每日汇率:搭在余额查询这条已有的 60 秒轮询上,**不新增定时器**。
|
|
5833
|
+
判据是「缓存为空 / 缓存早于今天 9:00」—— 9:00 之前一次都不拉,9:00 之后第一拍拉一次,
|
|
5834
|
+
当天再也不会重复。失败完全静默:汇率是显示用的辅助数据,拉不到就用上次那份。 */
|
|
5835
|
+
if (shouldRefresh(readCachedRate(), Date.now()) === true) {
|
|
5836
|
+
fetchAndCacheRate({ logger: (message) => logHost(ctx, message) })
|
|
5837
|
+
.catch(() => { /* 静默:汇率拉不到不影响余额 */ })
|
|
5838
|
+
}
|
|
5620
5839
|
const value = await queryBalance(ctx, force, url.searchParams.get('provider'), url.searchParams.get('model'))
|
|
5621
|
-
|
|
5840
|
+
/* 把当前汇率一并交给客户端:余额是「当下的钱」,它要用**当前**汇率折算,
|
|
5841
|
+
而汇率由 host 统一维护(每天 9:00 拉一次),客户端不必自己发请求。 */
|
|
5842
|
+
sendJson(res, 200, Object.assign({}, value, { probe: accountProbeNote, exchangeRate: currentExchangeRate() }))
|
|
5622
5843
|
}
|