dsh-aupdate 0.6.0 → 0.6.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 (4) hide show
  1. package/README.md +19 -0
  2. package/client.js +87 -13
  3. package/index.js +193 -60
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -141,12 +141,20 @@ mtime 为准:那是磁盘事实。会话目录整个读不到时返回「不
141
141
  「还没跑过」,看着像这一轮根本没跑过。读的时候逐字段校验,坏文件只会让这张卡缺席,
142
142
  不会让插件加载失败。
143
143
 
144
+ ### 显示语言
145
+
146
+ 设置页顶部有「显示语言」:跟随系统 / 中文 / English。切换立即生效,不用等保存往返;
147
+ 选择会存进 `~/.dsh/aupdate-settings.json`(键 `lang`),换个浏览器或换台机器打开设置页
148
+ 还是同一个语言。只影响文案,不改插件的更新行为。
149
+
144
150
  整页最下面是**运行日志**卡片,直接看插件最近写了什么,不用再去翻文件。日志正文用中文写,
145
151
  一行一件事(检查了多少个、装哪个、为什么跳过),状态词也翻成人话;
146
152
 
147
153
  - 可选显示最近 100 / 200 / 500 / 1000 行,默认 200
148
154
  - **最新的在最上面**:按时间倒序渲染,刚装了什么不用滚到底
149
155
  - 时间只到「月-日 时:分:秒」并等宽对齐,省下的宽度留给正文
156
+ - **正文跟着「显示语言」走**:文件里存的是事件码和参数,不是成品句子,所以在中文与
157
+ English 之间切换后,连历史行都会跟着变;0.6.1 之前写下的旧行是句子,原样保留
150
158
  - 打开「自动刷新」后每 5 秒拉一次,正在排查时开着;关掉就完全不动
151
159
  - 读之前会先把待写队列刷下去,所以刚点完检查,那几行马上就在里面
152
160
  - 时间戳按本地时区显示,文件超过 1MB 轮转给一句提示,另附总行数
@@ -356,6 +364,13 @@ why it failed) is persisted to `~/.dsh/aupdate-lastrun.json` and survives a rest
356
364
  used to live in memory only, so every restart reset the card to "never run" and looked
357
365
  like nothing had happened.
358
366
 
367
+ ### Display language
368
+
369
+ The page offers **Display language**: follow the system, 中文, or English. The switch
370
+ applies immediately without a save round-trip, and the choice is stored in
371
+ `~/.dsh/aupdate-settings.json` (key `lang`), so another browser or machine opens the page
372
+ in the same language. Wording only — it changes no update behaviour.
373
+
359
374
  ### Update notices
360
375
 
361
376
  When a check finds updates, a notice appears in the bottom-right corner listing each
@@ -386,6 +401,10 @@ live in `~/.dsh/aupdate-settings.json`.
386
401
  The page renders the log newest first, so whatever just happened is at the top of the
387
402
  box instead of at the bottom of a scroll.
388
403
 
404
+ Log lines are stored as an event code plus its arguments, not as finished sentences, so
405
+ switching **Display language** re-renders history too. Lines written before 0.6.2 are
406
+ sentences and stay exactly as they were.
407
+
389
408
  You can read this file straight from the settings page (see above). Point it
390
409
  elsewhere with `DSH_AUTO_UPDATE_LOG`.
391
410
 
package/client.js CHANGED
@@ -95,6 +95,11 @@ window.__ModuleLoader__.load({
95
95
  pkgsNotInstalled: '未安装',
96
96
  pkgsNoMatch: '没有匹配的插件',
97
97
  pageLabel: '插件更新',
98
+ language: '显示语言',
99
+ languageHint: '只换这个设置页和提醒的文案,不改插件的更新行为',
100
+ langAuto: '跟随系统',
101
+ langZh: '中文',
102
+ langEn: 'English',
98
103
  toastTitle: '{n} 个插件可以更新',
99
104
  toastMore: '还有 {n} 个',
100
105
  toastDismiss: '知道了',
@@ -195,6 +200,11 @@ window.__ModuleLoader__.load({
195
200
  pkgsNotInstalled: 'not installed',
196
201
  pkgsNoMatch: 'Nothing matches',
197
202
  pageLabel: 'Plugin updates',
203
+ language: 'Display language',
204
+ languageHint: 'Changes the wording of this page and its notices, not what the plugin updates',
205
+ langAuto: 'Follow the system',
206
+ langZh: '中文',
207
+ langEn: 'English',
198
208
  toastTitle: '{n} plugin(s) can update',
199
209
  toastMore: 'and {n} more',
200
210
  toastDismiss: 'Got it',
@@ -222,9 +232,50 @@ window.__ModuleLoader__.load({
222
232
  }
223
233
  }
224
234
 
225
- const IS_ZH = detectZh()
226
- const T = IS_ZH ? COPY.zh : COPY.en
227
- const LOCALE = IS_ZH ? 'zh-CN' : 'en-US'
235
+ /**
236
+ * 显示语言。
237
+ *
238
+ * 原来在模块加载时算一次就定死了:中文系统永远中文、英文系统永远英文,用户在
239
+ * 设置页里改不了。现在语言是可变状态——applyLang 换掉 T 并通知所有订阅者重渲染,
240
+ * 选择本身存进设置覆盖层(settings.lang),换个浏览器打开也还是这个选择。
241
+ */
242
+ const AUTOLANG = detectZh() ? 'zh' : 'en'
243
+ const LANG_CHOICES = ['auto', 'zh', 'en']
244
+ let LANG = AUTOLANG
245
+ let LOCALE = LANG === 'zh' ? 'zh-CN' : 'en-US'
246
+ let T = COPY[LANG]
247
+ const langListeners = new Set()
248
+
249
+ /** 把 auto / zh / en 落成实际语言;认不出的值一律当 auto。 */
250
+ function resolveLang(choice) {
251
+ return choice === 'zh' || choice === 'en' ? choice : AUTOLANG
252
+ }
253
+
254
+ function applyLang(choice) {
255
+ const next = resolveLang(choice)
256
+ if (next === LANG) return
257
+ LANG = next
258
+ LOCALE = LANG === 'zh' ? 'zh-CN' : 'en-US'
259
+ T = COPY[LANG]
260
+ for (const listener of langListeners) {
261
+ try { listener() } catch {}
262
+ }
263
+ }
264
+
265
+ /**
266
+ * 订阅语言变化。
267
+ *
268
+ * 每个直接渲染 T 的组件都要调一次:否则切换时只有拿到新状态的组件更新,其余部分
269
+ * 停在旧语言上——一页里中英混排,比不支持切换更难看。
270
+ */
271
+ function useLang() {
272
+ const [, force] = useState(0)
273
+ useEffect(() => {
274
+ const listener = () => force((n) => n + 1)
275
+ langListeners.add(listener)
276
+ return () => { langListeners.delete(listener) }
277
+ }, [])
278
+ }
228
279
 
229
280
  /**
230
281
  * 时间必须先转成浏览器本地时区再显示。
@@ -269,12 +320,12 @@ window.__ModuleLoader__.load({
269
320
  const when = new Date(iso)
270
321
  if (Number.isNaN(when.getTime())) return ''
271
322
  const minutes = Math.floor((Date.now() - when.getTime()) / 60000)
272
- if (minutes < 1) return IS_ZH ? '刚刚' : 'just now'
273
- if (minutes < 60) return IS_ZH ? minutes + ' 分钟前' : minutes + ' min ago'
323
+ if (minutes < 1) return LANG === 'zh' ? '刚刚' : 'just now'
324
+ if (minutes < 60) return LANG === 'zh' ? minutes + ' 分钟前' : minutes + ' min ago'
274
325
  const hours = Math.floor(minutes / 60)
275
- if (hours < 24) return IS_ZH ? hours + ' 小时前' : hours + ' h ago'
326
+ if (hours < 24) return LANG === 'zh' ? hours + ' 小时前' : hours + ' h ago'
276
327
  const days = Math.floor(hours / 24)
277
- return IS_ZH ? days + ' 天前' : days + ' d ago'
328
+ return LANG === 'zh' ? days + ' 天前' : days + ' d ago'
278
329
  }
279
330
 
280
331
  function endpoint(name) {
@@ -294,8 +345,10 @@ window.__ModuleLoader__.load({
294
345
  return response.json()
295
346
  }
296
347
 
297
- async function getLogs(lines) {
298
- const response = await fetch(endpoint('logs') + '?lines=' + encodeURIComponent(String(lines)), {
348
+ async function getLogs(lines, lang) {
349
+ // 日志在磁盘上存的是 code + 参数,正文由后端按这里要的语言渲染。
350
+ const wanted = lang === 'en' ? 'en' : 'zh'
351
+ const response = await fetch(endpoint('logs') + '?lines=' + encodeURIComponent(String(lines)) + '&lang=' + wanted, {
299
352
  headers: { accept: 'application/json' },
300
353
  cache: 'no-store',
301
354
  })
@@ -487,6 +540,7 @@ window.__ModuleLoader__.load({
487
540
  * 自己填的到底是不是想排除的那个。改成从 /state 拿到的已装清单直接勾。
488
541
  */
489
542
  function PackagePicker(props) {
543
+ useLang()
490
544
  const { packages, selected, onChange } = props
491
545
  const [query, setQuery] = useState('')
492
546
  const chosen = useMemo(() => new Set(Array.isArray(selected) ? selected : []), [selected])
@@ -547,6 +601,7 @@ window.__ModuleLoader__.load({
547
601
  }
548
602
 
549
603
  function AutoUpdateCard() {
604
+ useLang()
550
605
  const [state, setState] = useState(null)
551
606
  const [draft, setDraft] = useState(null)
552
607
  const [phase, setPhase] = useState('loading') // loading | ready | error
@@ -562,6 +617,8 @@ window.__ModuleLoader__.load({
562
617
  setPhase('loading')
563
618
  try {
564
619
  const next = await getState()
620
+ // 语言先落地再渲染:否则第一屏会先按系统语言画一次,再跳成用户选的。
621
+ applyLang(next?.settings?.lang)
565
622
  setState(next)
566
623
  setDraft(next.settings)
567
624
  setPhase('ready')
@@ -579,7 +636,7 @@ window.__ModuleLoader__.load({
579
636
 
580
637
  const dirty = useMemo(() => {
581
638
  if (state === null || draft === null) return false
582
- const keys = ['enabled', 'autoApply', 'hotReload', 'checkOnStart', 'idleOnly', 'notify', 'intervalMinutes', 'firstDelayMinutes', 'allowMajor', 'allowPrerelease', 'scheduleMode', 'dailyAt', 'everyHours', 'everyDays', 'suppressHours', 'maxPerCycle', 'sessionIdleMinutes']
639
+ const keys = ['lang', 'enabled', 'autoApply', 'hotReload', 'checkOnStart', 'idleOnly', 'notify', 'intervalMinutes', 'firstDelayMinutes', 'allowMajor', 'allowPrerelease', 'scheduleMode', 'dailyAt', 'everyHours', 'everyDays', 'suppressHours', 'maxPerCycle', 'sessionIdleMinutes']
583
640
  for (const key of keys) {
584
641
  if (draft[key] !== state.settings[key]) return true
585
642
  }
@@ -593,6 +650,7 @@ window.__ModuleLoader__.load({
593
650
  setSaveHint('')
594
651
  try {
595
652
  const next = await saveState({
653
+ lang: draft.lang,
596
654
  enabled: draft.enabled,
597
655
  autoApply: draft.autoApply,
598
656
  hotReload: draft.hotReload,
@@ -612,6 +670,7 @@ window.__ModuleLoader__.load({
612
670
  maxPerCycle: draft.maxPerCycle,
613
671
  sessionIdleMinutes: draft.sessionIdleMinutes,
614
672
  })
673
+ applyLang(next?.settings?.lang)
615
674
  setState(next)
616
675
  setDraft(next.settings)
617
676
  setSaveHint(T.saved + ' · ' + T.savedHint)
@@ -691,6 +750,18 @@ window.__ModuleLoader__.load({
691
750
  h('p', { style: S.sub }, T.subtitle),
692
751
  ),
693
752
  h('div', { style: S.card },
753
+ h(SelectRow, {
754
+ label: T.language,
755
+ hint: T.languageHint,
756
+ value: draft.lang ?? 'auto',
757
+ // 先切文案再落盘:切换要立刻看得见,不能等保存往返。
758
+ onChange: (v) => { patch('lang', v); applyLang(v) },
759
+ options: [
760
+ { value: 'auto', label: T.langAuto },
761
+ { value: 'zh', label: T.langZh },
762
+ { value: 'en', label: T.langEn },
763
+ ],
764
+ }),
694
765
  h(SwitchRow, { label: T.enabled, hint: T.enabledHint, value: draft.enabled, onChange: (v) => patch('enabled', v) }),
695
766
  h(SwitchRow, { label: T.autoApply, hint: T.autoApplyHint, value: draft.autoApply, onChange: (v) => patch('autoApply', v), disabled: !draft.enabled }),
696
767
  h(SwitchRow, { label: T.hotReload, hint: T.hotReloadHint, value: draft.hotReload, onChange: (v) => patch('hotReload', v), disabled: !draft.enabled }),
@@ -805,6 +876,7 @@ window.__ModuleLoader__.load({
805
876
  * 每 5 秒重渲染自己,不该把整张设置卡片连同输入框一起重渲染——那样光标会跳。
806
877
  */
807
878
  function LogCard() {
879
+ useLang()
808
880
  const [lines, setLines] = useState(200)
809
881
  const [data, setData] = useState(null)
810
882
  const [phase, setPhase] = useState('loading') // loading | ready | missing
@@ -813,15 +885,16 @@ window.__ModuleLoader__.load({
813
885
 
814
886
  const refresh = useCallback(async () => {
815
887
  try {
816
- const next = await getLogs(lines)
888
+ // LANG 进依赖:切换显示语言时这一栏要重新取,否则日志正文还是旧语言。
889
+ const next = await getLogs(lines, LANG)
817
890
  setData(next)
818
891
  setPhase(next?.exists === false ? 'missing' : 'ready')
819
892
  } catch {
820
893
  setPhase('missing')
821
894
  }
822
- }, [lines])
895
+ }, [lines, LANG])
823
896
 
824
- // lines 变了要立刻重取;tick 是自动刷新用来触发同一段逻辑的。
897
+ // lines 或语言变了要立刻重取;tick 是自动刷新用来触发同一段逻辑的。
825
898
  useEffect(() => { void refresh() }, [refresh, tick])
826
899
 
827
900
  useEffect(() => {
@@ -877,6 +950,7 @@ window.__ModuleLoader__.load({
877
950
  * summary 只报最关键的一件事——上次检查的结果,别把整页塞进一行。
878
951
  */
879
952
  function AutoUpdateSummary() {
953
+ useLang()
880
954
  const [state, setState] = useState(null)
881
955
  useEffect(() => {
882
956
  let alive = true
package/index.js CHANGED
@@ -91,37 +91,134 @@ function flushLog() {
91
91
  }
92
92
  }
93
93
 
94
- /** 日志里的状态词翻译成人话——面板是给人看的,不留英文状态码。 */
95
- const STATUS_TEXT = { done: '完成', blocked: '已让开', failed: '失败', skipped: '已跳过', none: '无', ok: '成功' }
96
-
97
- function statusText(value) {
98
- return STATUS_TEXT[String(value ?? '')] ?? String(value ?? '')
99
- }
100
-
101
- /** 设置页提交的键名,日志里不该出现 enabled,autoApply 这种字面量。 */
102
- const FIELD_LABELS = {
103
- enabled: '定时检查', autoApply: '自动安装', hotReload: '就地生效', checkOnStart: '启动先查',
104
- idleOnly: '忙时不动手', notify: '更新提醒', intervalMinutes: '检查间隔',
105
- firstDelayMinutes: '首次延迟', exclude: '不更新的包', allowMajor: '跨大版本',
106
- allowPrerelease: '预发布', scheduleMode: '调度方式', dailyAt: '每天时刻',
107
- everyHours: '每几小时', everyDays: '每几天', suppressHours: '失败抑制',
108
- maxPerCycle: '单轮上限', sessionIdleMinutes: '会话静默',
109
- }
94
+ /**
95
+ * 结构化日志。
96
+ *
97
+ * 0.6.1 及以前是把成品句子写进文件:中文环境下写中文,那一刻语言就钉死了,
98
+ * 之后在设置页切成 English,历史行仍然全是中文。要让日志跟着语言走,落盘的内容
99
+ * 就不能是句子——这里改成写 code + 参数(一行一个 JSON 数组),等到读取时
100
+ * 才按请求的语言渲染。想加一种语言只是多一张模板表。
101
+ *
102
+ * 兼容:旧格式的行是成品句子,解析失败就原样显示,不丢历史。
103
+ */
110
104
 
111
- function fieldLabel(key) {
112
- return FIELD_LABELS[key] ?? String(key)
105
+ /** 状态词。运行结果是数据(done/skipped/…),显示成哪种语言由读取侧决定。 */
106
+ const LOG_STATUS = {
107
+ zh: { done: '完成', blocked: '已让开', failed: '失败', skipped: '已跳过', none: '无', ok: '成功' },
108
+ en: { done: 'done', blocked: 'held off', failed: 'failed', skipped: 'skipped', none: 'none', ok: 'ok' },
109
+ }
110
+
111
+ /** 设置项在日志里的名字:enabled / autoApply 这种字面量不该出现在面板上。 */
112
+ const LOG_FIELD_LABELS = {
113
+ zh: {
114
+ lang: '显示语言', enabled: '定时检查', autoApply: '自动安装', hotReload: '就地生效',
115
+ checkOnStart: '启动先查', idleOnly: '忙时不动手', notify: '更新提醒',
116
+ intervalMinutes: '检查间隔', firstDelayMinutes: '首次延迟', exclude: '不更新的包',
117
+ allowMajor: '跨大版本', allowPrerelease: '预发布', scheduleMode: '调度方式',
118
+ dailyAt: '每天时刻', everyHours: '每几小时', everyDays: '每几天',
119
+ suppressHours: '失败抑制', maxPerCycle: '单轮上限', sessionIdleMinutes: '会话静默',
120
+ },
121
+ en: {
122
+ lang: 'display language', enabled: 'scheduled check', autoApply: 'auto-install',
123
+ hotReload: 'apply in place', checkOnStart: 'check on start', idleOnly: 'hold while busy',
124
+ notify: 'update notices', intervalMinutes: 'check interval', firstDelayMinutes: 'first delay',
125
+ exclude: 'never-update list', allowMajor: 'major upgrades', allowPrerelease: 'prereleases',
126
+ scheduleMode: 'schedule', dailyAt: 'time of day', everyHours: 'every N hours',
127
+ everyDays: 'every N days', suppressHours: 'failure suppression', maxPerCycle: 'per-cycle cap',
128
+ sessionIdleMinutes: 'session idle',
129
+ },
113
130
  }
114
131
 
115
- function yesNo(value) {
116
- return value === true ? '开' : '关'
132
+ function makeLogTemplates(lang) {
133
+ const S = LOG_STATUS[lang] ?? LOG_STATUS.zh
134
+ const labels = LOG_FIELD_LABELS[lang] ?? LOG_FIELD_LABELS.zh
135
+ const zh = lang !== 'en'
136
+ const sep = zh ? '、' : ', '
137
+ const status = (value) => S[String(value ?? '')] ?? String(value ?? '')
138
+ const list = (value) => (Array.isArray(value) ? value.join(sep) : String(value ?? ''))
139
+ const onOff = (value) => (zh ? (value === true ? '开' : '关') : (value === true ? 'on' : 'off'))
140
+ return {
141
+ raw: (text) => String(text ?? ''),
142
+ checked: (n, u) => (zh ? `检查 ${n} 个插件,${u} 个可更新` : `Checked ${n} plugin(s), ${u} update(s) available`),
143
+ capped: (max, left) => (zh ? `本轮限量装 ${max} 个,剩下 ${left} 个下一轮再装` : `Capped at ${max} install(s) this cycle; ${left} left for the next round`),
144
+ skipInstall: (why) => (zh ? `跳过安装:${list(why)}` : `Skipped installing: ${list(why)}`),
145
+ snapshotTaken: (dir, files) => (zh ? `已留快照 ${dir}(${list(files)})` : `Snapshot saved to ${dir} (${list(files)})`),
146
+ snapshotFailed: (msg) => (zh ? `留快照失败:${msg}` : `Snapshot failed: ${msg}`),
147
+ tookOverLock: (minutes) => (zh ? `接管了一个已挂 ${minutes} 分钟的安装锁` : `Took over an install lock left for ${minutes} min`),
148
+ install: (name, target, ok, detail) => (zh
149
+ ? `安装 ${name}@${target} → ${ok ? '成功' : '失败:' + (detail || '')}`
150
+ : `Installed ${name}@${target} → ${ok ? 'ok' : 'failed: ' + (detail || '')}`),
151
+ hotApply: (state, reason) => (zh
152
+ ? `就地生效 → ${status(state)}${reason ? ':' + reason : ''}`
153
+ : `Hot apply → ${status(state)}${reason ? ': ' + reason : ''}`),
154
+ cycle: (mode, state, reason) => (zh
155
+ ? `本轮${mode === 'check' ? '检查' : '更新'} → ${status(state)}:${reason}`
156
+ : `Cycle ${mode === 'check' ? 'check' : 'update'} → ${status(state)}: ${reason}`),
157
+ cycleFailed: (reason) => (zh ? `本轮失败:${reason}` : `Cycle failed: ${reason}`),
158
+ cycleThrew: (msg) => (zh ? `本轮抛错:${msg}` : `Cycle threw: ${msg}`),
159
+ rollback: (name, from, to, ok, detail) => (zh
160
+ ? `回滚 ${name} ${to} → ${from} → ${ok ? '成功' : '失败:' + (detail || '')}`
161
+ : `Rolled back ${name} ${to} → ${from} → ${ok ? 'ok' : 'failed: ' + (detail || '')}`),
162
+ rollbackRequest: (name, ok, reason) => (zh
163
+ ? `收到回滚请求 ${name} → ${ok ? '成功' : '失败:' + (reason || '')}`
164
+ : `Rollback requested for ${name} → ${ok ? 'ok' : 'failed: ' + (reason || '')}`),
165
+ settingsChanged: (keys) => (zh
166
+ ? `设置页改了:${list((Array.isArray(keys) ? keys : []).map((key) => labels[key] ?? String(key)))}`
167
+ : `Settings changed: ${list((Array.isArray(keys) ? keys : []).map((key) => labels[key] ?? String(key)))}`),
168
+ rescheduleFailed: (msg) => (zh ? `重排定时失败:${msg}` : `Rescheduling failed: ${msg}`),
169
+ toolFailed: (msg) => (zh ? `工具调用失败:${msg}` : `Tool call failed: ${msg}`),
170
+ toolUnavailable: (msg) => (zh ? `无法提供工具:${msg}` : `Could not offer the tool: ${msg}`),
171
+ toolRegistered: (ok) => (zh ? `工具注册:${ok ? '成功' : '失败'}` : `Tool registered: ${ok ? 'ok' : 'failed'}`),
172
+ toolRegisterThrew: (msg) => (zh ? `注册工具时抛错:${msg}` : `Tool registration threw: ${msg}`),
173
+ routeFailed: (msg) => (zh ? `接口处理出错:${msg}` : `Route failed: ${msg}`),
174
+ routeReady: (prefix) => (zh ? `设置接口已就绪:${prefix}` : `Settings route ready: ${prefix}`),
175
+ routeReadyNoScope: (prefix) => (zh ? `设置接口已就绪(没有 effect 作用域):${prefix}` : `Settings route ready (no effect scope): ${prefix}`),
176
+ routeRegisterFailed: (msg) => (zh ? `无法注册设置接口:${msg}` : `Could not register the settings route: ${msg}`),
177
+ routeRegisterThrew: (msg) => (zh ? `注册设置接口时抛错:${msg}` : `Route registration threw: ${msg}`),
178
+ webServerMissing: () => (zh ? '没有 webServer 服务,设置页会显示不可用' : 'No webServer service; the settings page will report it'),
179
+ toolScopeEnded: (msg) => (zh ? `工具作用域已结束:${msg}` : `Tool scope ended: ${msg}`),
180
+ disabledBySettings: () => (zh ? '设置里已关闭自动更新,定时器待命' : 'Auto-update is off in settings; scheduler parked'),
181
+ disabledByConfig: () => (zh ? '配置里已关闭自动更新,定时器待命,设置页仍然可用' : 'Auto-update is off in config; scheduler parked, settings page stays live'),
182
+ ready: (minutes, autoApply, hotReload) => (zh
183
+ ? `已就绪:每 ${minutes} 分钟检查一次,自动安装=${onOff(autoApply)},就地生效=${onOff(hotReload)}`
184
+ : `Ready: every ${minutes} min, autoApply=${onOff(autoApply)}, hotReload=${onOff(hotReload)}`),
185
+ }
186
+ }
187
+
188
+ const LOG_TEMPLATES = { zh: makeLogTemplates('zh'), en: makeLogTemplates('en') }
189
+
190
+ /** 只认 zh / en;其余(含 undefined)按中文渲染。 */
191
+ function logLangOf(choice) {
192
+ return choice === 'en' ? 'en' : 'zh'
193
+ }
194
+
195
+ /** 渲染一条日志。认不出的 code 退化成一串参数,至少不丢信息。 */
196
+ function renderLogEntry(code, args, lang) {
197
+ const table = LOG_TEMPLATES[logLangOf(lang)]
198
+ const values = Array.isArray(args) ? args : []
199
+ const render = table[String(code)]
200
+ if (typeof render !== 'function') return '[' + String(code) + '] ' + values.join(' ')
201
+ try {
202
+ return render(...values)
203
+ } catch {
204
+ return '[' + String(code) + '] ' + values.join(' ')
205
+ }
117
206
  }
118
207
 
119
- function writeLog(message) {
208
+ /**
209
+ * 写一条日志。
210
+ *
211
+ * @param code 模板名(见 makeLogTemplates),不是成品句子。
212
+ * @param args 模板参数;自由文本走 raw。
213
+ */
214
+ function writeLog(code, args = []) {
215
+ const values = Array.isArray(args) ? args : []
120
216
  try {
121
- console.log('[dsh-aupdate] ' + oneLine(message, 400))
217
+ // 控制台固定中文:那是给开发者看的,跟界面语言无关。
218
+ console.log('[dsh-aupdate] ' + oneLine(renderLogEntry(code, values, 'zh'), 400))
122
219
  } catch {}
123
220
  try {
124
- logQueue.push('[' + new Date().toISOString() + '] ' + oneLine(message) + '\n')
221
+ logQueue.push('[' + new Date().toISOString() + '] ' + oneLine(JSON.stringify([String(code), ...values])) + '\n')
125
222
  // 队列异常长说明写盘一直失败,直接丢掉最老的,避免吃内存。
126
223
  if (logQueue.length > 500) logQueue = logQueue.slice(-500)
127
224
  if (!logFlushing) {
@@ -149,7 +246,7 @@ const LOG_TAIL_MAX_LINES = 1000
149
246
  * 面板里却没有这一行」——差的就是 setImmediate 那一拍。
150
247
  * 读不到不算错误:可能从没跑过检查,也可能用户把文件删了。
151
248
  */
152
- function readLogTail(limit) {
249
+ function readLogTail(limit, lang) {
153
250
  try {
154
251
  flushLogNow()
155
252
  } catch {}
@@ -165,9 +262,24 @@ function readLogTail(limit) {
165
262
  // 每个进程都会补换行,split 后末尾必然多一个空串。
166
263
  if (all.length > 0 && all[all.length - 1] === '') all.pop()
167
264
  const rows = []
265
+ const wanted = logLangOf(lang)
168
266
  for (const line of all.slice(-want)) {
169
267
  const match = /^\[([^\]]+)\] ([\s\S]*)$/u.exec(line)
170
- rows.push(match === null ? { at: '', text: line } : { at: match[1], text: match[2] })
268
+ if (match === null) {
269
+ rows.push({ at: '', text: line })
270
+ continue
271
+ }
272
+ const body = match[2]
273
+ // 新格式是 JSON 数组;0.6.1 及更早写的是成品句子,解析不出就原样显示。
274
+ let parsed = null
275
+ if (body.startsWith('[')) {
276
+ try { parsed = JSON.parse(body) } catch {}
277
+ }
278
+ if (Array.isArray(parsed) && typeof parsed[0] === 'string') {
279
+ rows.push({ at: match[1], text: renderLogEntry(parsed[0], parsed.slice(1), wanted) })
280
+ } else {
281
+ rows.push({ at: match[1], text: body })
282
+ }
171
283
  }
172
284
  let size = 0
173
285
  try {
@@ -254,6 +366,8 @@ const OVERRIDEABLE = [
254
366
  // 只活在覆盖层里——Config 的字段类型是宿主校验的,加错一个类型
255
367
  // 会在加载期直接抛错,而覆盖层是我们自己的文件,改坏了只影响这一项。
256
368
  'scheduleMode', 'dailyAt', 'everyHours', 'everyDays', 'suppressHours',
369
+ // 界面显示语言。存这里而不是浏览器里:换台机器、换个浏览器打开,选择还在。
370
+ 'lang',
257
371
  // 效率闸门:一轮最多装几个、会话多静才算闲。
258
372
  'maxPerCycle', 'sessionIdleMinutes',
259
373
  ]
@@ -261,6 +375,19 @@ const OVERRIDEABLE = [
261
375
  /** 四种调度模式。minutes 是原来的「间隔 N 分钟」,其余照抄竞品。 */
262
376
  const SCHEDULE_MODES = ['minutes', 'hours', 'days', 'daily']
263
377
 
378
+ /**
379
+ * 界面语言。auto = 跟随系统(中文环境给中文,其余给英文)。
380
+ *
381
+ * 之所以要存到设置层而不是只留在 localStorage:这个值决定整页文案,
382
+ * 换个浏览器或换台机器打开设置页时,用户不该再选一次。
383
+ */
384
+ const LANG_CHOICES = ['auto', 'zh', 'en']
385
+
386
+ function langOf(config) {
387
+ const text = typeof config?.lang === 'string' ? config.lang.trim().toLowerCase() : ''
388
+ return LANG_CHOICES.includes(text) ? text : 'auto'
389
+ }
390
+
264
391
  /** 数值型覆盖项的边界:写坏了钳进范围,而不是让设置页把插件配废。 */
265
392
  const NUMBER_BOUNDS = {
266
393
  intervalMinutes: [10, 10080],
@@ -322,6 +449,11 @@ function writeOverrides(patch) {
322
449
  if (SCHEDULE_MODES.includes(text)) next[key] = text
323
450
  continue
324
451
  }
452
+ if (key === 'lang') {
453
+ const text = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
454
+ if (LANG_CHOICES.includes(text)) next[key] = text
455
+ continue
456
+ }
325
457
  const bounds = NUMBER_BOUNDS[key]
326
458
  if (bounds !== undefined) {
327
459
  const value = typeof raw === 'number' ? raw : Number(raw)
@@ -414,6 +546,7 @@ function settingsOf(config) {
414
546
  allowPrerelease: booleanSetting(config, 'allowPrerelease', false),
415
547
  // 调度模式:intervalMinutes 只在 minutes 模式下生效,
416
548
  // 其余三种各有自己的参数,切模式不丢原来的值。
549
+ lang: langOf(config),
417
550
  scheduleMode: scheduleModeOf(config),
418
551
  dailyAt: clockOf(config, 'dailyAt', '03:00'),
419
552
  everyHours: numberSetting(config, 'everyHours', 6, 1, 168),
@@ -1116,7 +1249,7 @@ function snapshotProfile(profileDir, now) {
1116
1249
  return { dir, files: saved }
1117
1250
  } catch (error) {
1118
1251
  // 留底失败不该拦住更新本身:它只是事后证据,不是前置条件。
1119
- writeLog('留快照失败:' + oneLine(error?.message ?? error, 200))
1252
+ writeLog('snapshotFailed', [oneLine(error?.message ?? error, 200)])
1120
1253
  return null
1121
1254
  }
1122
1255
  }
@@ -1175,7 +1308,7 @@ function takeProfileLock(profileDir, now) {
1175
1308
  } catch {}
1176
1309
  try {
1177
1310
  writeFileSync(file, stamp + '\n', { encoding: 'utf8', flag: 'wx' })
1178
- writeLog('接管了一个已挂 ' + ageMinutes + ' 分钟的安装锁')
1311
+ writeLog('tookOverLock', [ageMinutes])
1179
1312
  return { ok: true, file }
1180
1313
  } catch (error) {
1181
1314
  return { ok: false, reason: '抢锁失败:' + oneLine(error?.message ?? error, 160) }
@@ -1345,7 +1478,7 @@ async function runCycle(mode, ctxRef) {
1345
1478
  else report.skipped.push(answer)
1346
1479
  }
1347
1480
  }
1348
- writeLog('检查 ' + report.checked + ' 个插件,' + report.updates.length + ' 个可更新')
1481
+ writeLog('checked', [report.checked, report.updates.length])
1349
1482
  if (report.updates.length === 0) {
1350
1483
  report.reason = '没有可更新的插件'
1351
1484
  return report
@@ -1355,7 +1488,7 @@ async function runCycle(mode, ctxRef) {
1355
1488
  const deferred = settings.maxPerCycle > 0 ? report.updates.length - settings.maxPerCycle : 0
1356
1489
  if (deferred > 0) {
1357
1490
  report.updates = report.updates.slice(0, settings.maxPerCycle)
1358
- writeLog('本轮限量装 ' + settings.maxPerCycle + ' 个,剩下 ' + deferred + ' 个下一轮再装')
1491
+ writeLog('capped', [settings.maxPerCycle, deferred])
1359
1492
  }
1360
1493
  if (mode === 'check' || !settings.autoApply) {
1361
1494
  report.reason = '只查不装'
@@ -1370,7 +1503,7 @@ async function runCycle(mode, ctxRef) {
1370
1503
  if (why.length > 0) {
1371
1504
  report.status = 'blocked'
1372
1505
  report.reason = why.join(';') + ',这一轮不安装'
1373
- writeLog('跳过安装:' + why.join(';'))
1506
+ writeLog('skipInstall', [why])
1374
1507
  return report
1375
1508
  }
1376
1509
  }
@@ -1385,7 +1518,7 @@ async function runCycle(mode, ctxRef) {
1385
1518
  if (!lock.ok) {
1386
1519
  report.status = 'blocked'
1387
1520
  report.reason = lock.reason
1388
- writeLog('跳过安装:' + lock.reason)
1521
+ writeLog('skipInstall', [lock.reason])
1389
1522
  return report
1390
1523
  }
1391
1524
  try {
@@ -1393,7 +1526,7 @@ async function runCycle(mode, ctxRef) {
1393
1526
  const snapshot = snapshotProfile(profileDir, new Date())
1394
1527
  if (snapshot !== null) {
1395
1528
  report.snapshot = snapshot.dir
1396
- writeLog('已留快照 ' + snapshot.dir + '(' + snapshot.files.join('、') + ')')
1529
+ writeLog('snapshotTaken', [snapshot.dir, snapshot.files])
1397
1530
  }
1398
1531
  return await applyUpdates(ctxRef, report, settings, runner, profileDir, profileName)
1399
1532
  } finally {
@@ -1402,7 +1535,7 @@ async function runCycle(mode, ctxRef) {
1402
1535
  } catch (error) {
1403
1536
  report.status = 'failed'
1404
1537
  report.reason = oneLine(error?.message ?? error, 400)
1405
- writeLog('本轮失败:' + report.reason)
1538
+ writeLog('cycleFailed', [report.reason])
1406
1539
  return report
1407
1540
  } finally {
1408
1541
  report.finishedAt = new Date().toISOString()
@@ -1411,7 +1544,7 @@ async function runCycle(mode, ctxRef) {
1411
1544
  at: report.finishedAt,
1412
1545
  checked: report.checked,
1413
1546
  updates: report.updates.map((item) => item.name + ' ' + (item.current ?? '?') + ' -> ' + item.target),
1414
- installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' 失败')),
1547
+ installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' !failed')),
1415
1548
  reload: report.reload?.status ?? 'none',
1416
1549
  reason: report.reason,
1417
1550
  snapshot: report.snapshot,
@@ -1431,7 +1564,7 @@ async function applyUpdates(ctxRef, report, settings, runner, profileDir, profil
1431
1564
  for (const update of ordered) {
1432
1565
  const outcome = await installOne(runner, profileName, profileDir, update.name, update.target)
1433
1566
  report.installed.push(outcome)
1434
- writeLog('安装 ' + update.name + '@' + update.target + ' → ' + (outcome.ok ? '成功' : '失败:' + outcome.detail))
1567
+ writeLog('install', [update.name, update.target, outcome.ok === true, outcome.detail ?? ''])
1435
1568
  if (outcome.ok) {
1436
1569
  clearFailure(update.name, update.target)
1437
1570
  appendHistory({
@@ -1468,7 +1601,7 @@ async function applyUpdates(ctxRef, report, settings, runner, profileDir, profil
1468
1601
  return report
1469
1602
  }
1470
1603
  report.reload = await hotApply(ctxRef.ctx, requiredBefore)
1471
- writeLog('就地生效 → ' + statusText(report.reload.status) + (report.reload.reason ? ':' + report.reload.reason : ''))
1604
+ writeLog('hotApply', [report.reload.status, report.reload.reason ?? ''])
1472
1605
  report.reason = '已安装 ' + okCount + ' 个;' + (report.reload.reason ?? '')
1473
1606
  if (report.reload.status === 'failed') report.status = 'failed'
1474
1607
  else if (report.reload.status === 'blocked' || report.reload.status === 'restart') report.status = 'partial'
@@ -1531,7 +1664,7 @@ async function rollbackOne(ctxRef, entryName) {
1531
1664
  } finally {
1532
1665
  releaseProfileLock(lock)
1533
1666
  }
1534
- writeLog('回滚 ' + row.name + ' ' + row.to + ' → ' + row.from + ' → ' + (outcome.ok ? '成功' : '失败:' + outcome.detail))
1667
+ writeLog('rollback', [row.name, row.from, row.to, outcome.ok === true, outcome.detail ?? ''])
1535
1668
  if (!outcome.ok) return { ok: false, reason: outcome.detail }
1536
1669
  const next = rows.slice()
1537
1670
  next.unshift({
@@ -1610,19 +1743,19 @@ function registerTool(ctx, config) {
1610
1743
  reason: report.reason || '',
1611
1744
  checked: report.checked,
1612
1745
  updates: report.updates.map((item) => item.name + ' ' + (item.current ?? '?') + ' -> ' + item.target),
1613
- installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' 失败')),
1746
+ installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' !failed')),
1614
1747
  reload: report.reload?.status ?? 'none',
1615
1748
  skipped: report.skipped.map((item) => item.name + ':' + item.why),
1616
1749
  }
1617
1750
  } catch (error) {
1618
- writeLog('工具调用失败:' + oneLine(error?.message ?? error, 300))
1751
+ writeLog('toolFailed', [oneLine(error?.message ?? error, 300)])
1619
1752
  return { status: 'failed', reason: '没能完成,插件状态需要核对', checked: 0, updates: [], installed: [], reload: 'none' }
1620
1753
  }
1621
1754
  },
1622
1755
  }), 'dsh-aupdate: plugin_updater')
1623
1756
  return true
1624
1757
  } catch (error) {
1625
- writeLog('无法提供工具:' + oneLine(error?.message ?? error, 300))
1758
+ writeLog('toolUnavailable', [oneLine(error?.message ?? error, 300)])
1626
1759
  return false
1627
1760
  }
1628
1761
  }
@@ -1814,7 +1947,7 @@ function registerRoutes(scope, ctxRef) {
1814
1947
  return
1815
1948
  }
1816
1949
  if (suffix === '/logs') {
1817
- sendJson(res, 200, readLogTail(url.searchParams.get('lines')))
1950
+ sendJson(res, 200, readLogTail(url.searchParams.get('lines'), url.searchParams.get('lang')))
1818
1951
  return
1819
1952
  }
1820
1953
  sendJson(res, 404, { error: 'unknown endpoint' })
@@ -1832,12 +1965,12 @@ function registerRoutes(scope, ctxRef) {
1832
1965
  sendJson(res, 500, { error: result.error })
1833
1966
  return
1834
1967
  }
1835
- writeLog('设置页改了:' + Object.keys(body).map(fieldLabel).join('、'))
1968
+ writeLog('settingsChanged', [Object.keys(body)])
1836
1969
  // 改完立刻按新设置重排,否则要等下一次触发才换节奏。
1837
1970
  try {
1838
1971
  if (typeof ctxRef.reschedule === 'function') ctxRef.reschedule()
1839
1972
  } catch (error) {
1840
- writeLog('重排定时失败:' + oneLine(error?.message ?? error, 200))
1973
+ writeLog('rescheduleFailed', [oneLine(error?.message ?? error, 200)])
1841
1974
  }
1842
1975
  sendJson(res, 200, settingsSnapshot(ctxRef.config, ctxRef))
1843
1976
  return
@@ -1850,7 +1983,7 @@ function registerRoutes(scope, ctxRef) {
1850
1983
  return
1851
1984
  }
1852
1985
  const outcome = await rollbackOne(ctxRef, target)
1853
- writeLog('收到回滚请求 ' + target + ' → ' + (outcome.ok ? '成功' : '失败:' + outcome.reason))
1986
+ writeLog('rollbackRequest', [target, outcome.ok === true, outcome.reason ?? ''])
1854
1987
  sendJson(res, outcome.ok ? 200 : 409, outcome)
1855
1988
  return
1856
1989
  }
@@ -1870,7 +2003,7 @@ function registerRoutes(scope, ctxRef) {
1870
2003
  }
1871
2004
  sendJson(res, 405, { error: 'method not allowed' })
1872
2005
  } catch (error) {
1873
- writeLog('接口处理出错:' + oneLine(error?.message ?? error, 300))
2006
+ writeLog('routeFailed', [oneLine(error?.message ?? error, 300)])
1874
2007
  try { sendJson(res, 500, { error: 'internal' }) } catch {}
1875
2008
  }
1876
2009
  }
@@ -1879,14 +2012,14 @@ function registerRoutes(scope, ctxRef) {
1879
2012
  const register = () => webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler })
1880
2013
  if (typeof effect === 'function') {
1881
2014
  effect.call(scope, register, 'dsh-aupdate: settings routes')
1882
- writeLog('设置接口已就绪:' + ROUTE_PREFIX)
2015
+ writeLog('routeReady', [ROUTE_PREFIX])
1883
2016
  return true
1884
2017
  }
1885
2018
  register()
1886
- writeLog('设置接口已就绪(没有 effect 作用域):' + ROUTE_PREFIX)
2019
+ writeLog('routeReadyNoScope', [ROUTE_PREFIX])
1887
2020
  return true
1888
2021
  } catch (error) {
1889
- writeLog('无法注册设置接口:' + oneLine(error?.message ?? error, 300))
2022
+ writeLog('routeRegisterFailed', [oneLine(error?.message ?? error, 300)])
1890
2023
  return false
1891
2024
  }
1892
2025
  }
@@ -1905,15 +2038,15 @@ export function apply(ctx, config) {
1905
2038
  try {
1906
2039
  const tools = serviceOf(scope, 'tools')
1907
2040
  if (tools === null || typeof tools.register !== 'function') {
1908
- writeLog('工具注册失败')
2041
+ writeLog('toolRegistered', [false])
1909
2042
  return
1910
2043
  }
1911
2044
  if (toolService === tools) return
1912
2045
  toolService = tools
1913
2046
  const ok = registerTool(scope, config)
1914
- writeLog('工具注册:' + (ok ? '成功' : '失败'))
2047
+ writeLog('toolRegistered', [ok === true])
1915
2048
  } catch (error) {
1916
- writeLog('注册工具时抛错:' + oneLine(error?.message ?? error, 300))
2049
+ writeLog('toolRegisterThrew', [oneLine(error?.message ?? error, 300)])
1917
2050
  }
1918
2051
  }
1919
2052
  // 路由和工具是同一类问题:apply 执行时 webServer 可能还没就绪,
@@ -1923,14 +2056,14 @@ export function apply(ctx, config) {
1923
2056
  try {
1924
2057
  const webServer = serviceOf(scope, 'webServer')
1925
2058
  if (webServer === null || typeof webServer.register !== 'function') {
1926
- writeLog('没有 webServer 服务,设置页会显示不可用')
2059
+ writeLog('webServerMissing', [])
1927
2060
  return
1928
2061
  }
1929
2062
  if (routeService === webServer) return
1930
2063
  const ok = registerRoutes(scope, ctxRef)
1931
2064
  if (ok) routeService = webServer
1932
2065
  } catch (error) {
1933
- writeLog('注册设置接口时抛错:' + oneLine(error?.message ?? error, 300))
2066
+ writeLog('routeRegisterThrew', [oneLine(error?.message ?? error, 300)])
1934
2067
  }
1935
2068
  }
1936
2069
  const inject = propOf(ctx, 'inject')
@@ -1944,10 +2077,10 @@ export function apply(ctx, config) {
1944
2077
  offerRoutes(scope)
1945
2078
  })
1946
2079
  Promise.resolve(fiber).catch((error) => {
1947
- writeLog('工具作用域已结束:' + oneLine(error?.message ?? error, 300))
2080
+ writeLog('toolScopeEnded', [oneLine(error?.message ?? error, 300)])
1948
2081
  })
1949
2082
  } catch (error) {
1950
- writeLog('无法提供工具:' + oneLine(error?.message ?? error, 300))
2083
+ writeLog('toolUnavailable', [oneLine(error?.message ?? error, 300)])
1951
2084
  offerTool(ctx)
1952
2085
  offerRoutes(ctx)
1953
2086
  }
@@ -1960,9 +2093,9 @@ export function apply(ctx, config) {
1960
2093
  const go = async () => {
1961
2094
  try {
1962
2095
  const report = await beginningRun(mode, ctxRef)
1963
- if (report !== null) writeLog('本轮' + (mode === 'check' ? '检查' : '更新') + ' → ' + statusText(report.status) + ':' + report.reason)
2096
+ if (report !== null) writeLog('cycle', [mode, report.status, report.reason])
1964
2097
  } catch (error) {
1965
- writeLog('本轮抛错:' + oneLine(error?.message ?? error, 300))
2098
+ writeLog('cycleThrew', [oneLine(error?.message ?? error, 300)])
1966
2099
  }
1967
2100
  }
1968
2101
  void go()
@@ -1997,7 +2130,7 @@ export function apply(ctx, config) {
1997
2130
  clearScheduled()
1998
2131
  const live = settingsOf(ctxRef.config)
1999
2132
  if (!live.enabled) {
2000
- writeLog('设置里已关闭自动更新,定时器待命')
2133
+ writeLog('disabledBySettings', [])
2001
2134
  return
2002
2135
  }
2003
2136
  // 启动后第一次仍然只看 firstDelayMinutes,之后按当前调度模式算。
@@ -2031,7 +2164,7 @@ export function apply(ctx, config) {
2031
2164
 
2032
2165
  // 设置页要能读到运行状态并改设置,所以路由最后注册、且与 enabled 无关:
2033
2166
  // 关掉定时检查之后,用户仍然要能看到这一页并把它重新打开。
2034
- if (!settings.enabled) writeLog('配置里已关闭自动更新,定时器待命,设置页仍然可用')
2167
+ if (!settings.enabled) writeLog('disabledByConfig', [])
2035
2168
 
2036
2169
  const stop = () => {
2037
2170
  for (const off of timers.splice(0)) {
@@ -2047,7 +2180,7 @@ export function apply(ctx, config) {
2047
2180
  } catch {}
2048
2181
  }
2049
2182
 
2050
- writeLog('已就绪:每 ' + settings.intervalMinutes + ' 分钟检查一次,自动安装=' + yesNo(settings.autoApply) + ',就地生效=' + yesNo(settings.hotReload))
2183
+ writeLog('ready', [settings.intervalMinutes, settings.autoApply === true, settings.hotReload === true])
2051
2184
  }
2052
2185
 
2053
2186
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aupdate",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
5
  "description": "定时检查 DSH 插件更新,串行安装后就地生效,不重启;支持多种调度节奏、失败抑制、按包回滚,并在动手前留快照、忙时自动让开;不更新/只更新哪些插件改成勾选,发现更新在右下角提醒,日志最新在最上面,并在「设置 → 插件更新」里有独立一页。",
6
6
  "license": "MIT",