@andy.ian/dsh-homing 2.2.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/app-proxy.mjs CHANGED
@@ -109,7 +109,7 @@ export function proxyLocalAppHttp({ req, res, url, app, rest, clientIp, maxBodyB
109
109
  }, (upstreamRes) => {
110
110
  upstream.setTimeout(0)
111
111
  if (shouldBlockActiveContent(app, upstreamRes.headers['content-type'])) {
112
- audit('app-active-content-blocked', { app: app.id, contentType: String(upstreamRes.headers['content-type'] ?? '').slice(0, 100) })
112
+ audit('app-active-content-blocked', { app: app.id, contentType: String(upstreamRes.headers['content-type']).slice(0, 100) })
113
113
  upstreamRes.destroy()
114
114
  sendProxyError(req, res, app, 403, '此应用未开启「信任网页脚本」。API/文本仍可使用;如确认应用代码可信,请在应用管理中显式开启。')
115
115
  return
@@ -0,0 +1,57 @@
1
+ /**
2
+ * 页面加载守卫:每次页面加载都问一次「现在登录还成立吗」。
3
+ *
4
+ * 为什么必须存在(2026-11-15 事故):
5
+ * 手机把首页 HTML 缓存在本地后,浏览器根本不再请求 `/`(审计里只有图标请求、没有 `/`)。
6
+ * 于是服务端的「未登录 → 303 /login」永远不会触发:缓存里的旧页面壳照样启动,
7
+ * 它发起的 RPC/WebSocket 因为没有 Cookie 被拒,界面就永远停在转圈。
8
+ *
9
+ * 这个脚本跟着页面壳一起跑,在**每一次加载**时向服务端要一次真实状态(no-store,不可缓存):
10
+ * 未登录 / 会话已失效 → 立刻 replace 到 /login?next=当前页面。
11
+ *
12
+ * 注意:它必须是外部文件(页面 CSP 是 script-src 'self',内联脚本会被丢弃)。
13
+ */
14
+ (() => {
15
+ const CHECK_URL = '/dsh_homing/auth-state'
16
+ const LOOP_KEY = 'dsh-homing-auth-guard-at'
17
+
18
+ function toLogin(reason) {
19
+ // 防抖:10 秒内只跳一次,避免和浏览器自身的跳转打架造成闪烁
20
+ try {
21
+ const last = Number(sessionStorage.getItem(LOOP_KEY) ?? '0')
22
+ if (Number.isFinite(last) && Date.now() - last < 10_000) return
23
+ sessionStorage.setItem(LOOP_KEY, String(Date.now()))
24
+ } catch (error) {
25
+ // sessionStorage 不可用时也允许跳转
26
+ }
27
+ const here = location.pathname + location.search
28
+ const next = here.startsWith('/login') ? '' : here
29
+ const target = next === '' ? '/login' : '/login?next=' + encodeURIComponent(next)
30
+ console.warn('[dsh-homing] 未登录或会话已失效,前往登录页', reason ?? '')
31
+ location.replace(target)
32
+ }
33
+
34
+ async function check() {
35
+ // 已经在登录页 / 重置页就不用再检查,避免自己跳自己
36
+ if (location.pathname === '/login' || location.pathname === '/dsh_homing/reset') return
37
+ try {
38
+ const response = await fetch(CHECK_URL, {
39
+ cache: 'no-store',
40
+ credentials: 'same-origin',
41
+ headers: { accept: 'application/json' },
42
+ })
43
+ if (!response.ok) return // 服务端异常时不误伤,交给页面自身处理
44
+ const state = await response.json()
45
+ if (!state || state.authenticated !== false) return
46
+ toLogin(state.reason)
47
+ } catch (error) {
48
+ // 网络断了不要乱跳:此时跳登录页也没用
49
+ }
50
+ }
51
+
52
+ // 页面壳可能在 DOM 之前就渲染,尽早检查;同时等 DOMContentLoaded 再查一次兜底
53
+ void check()
54
+ if (document.readyState === 'loading') {
55
+ document.addEventListener('DOMContentLoaded', () => { void check() }, { once: true })
56
+ }
57
+ })()
@@ -0,0 +1,168 @@
1
+ /**
2
+ * 客户端错误上报(注入到 DSH 页面里)。
3
+ *
4
+ * 只做三件轻量的事(2026-11-15 排查结束后已删掉当时临时加的重负载探针):
5
+ *
6
+ * 1. 捕获 window.onerror / unhandledrejection / 资源加载失败 → 立即上报
7
+ * 2. 捕获 console.error / console.warn 的前 2 条(插件初始化失败常被应用
8
+ * try/catch 后写 logger,window.onerror 看不到)
9
+ * 3. 12 秒后若仍在启动页:先自动换 URL 重载一次,仍不行则显示自救提示
10
+ *
11
+ * 必须是外部文件(页面 CSP 只有 script-src 'self')。
12
+ */
13
+ (() => {
14
+ const REPORT_URL = '/dsh_homing/client-error'
15
+ const sent = new Set()
16
+
17
+ function report(payload) {
18
+ const key = (payload.kind ?? '') + '|' + String(payload.message ?? '').slice(0, 60)
19
+ if (sent.has(key)) return
20
+ sent.add(key)
21
+ try {
22
+ const body = JSON.stringify({
23
+ ...payload,
24
+ href: location.href,
25
+ ua: navigator.userAgent.slice(0, 120),
26
+ at: new Date().toISOString(),
27
+ })
28
+ fetch(REPORT_URL, {
29
+ method: 'POST',
30
+ headers: { 'content-type': 'application/json' },
31
+ body,
32
+ cache: 'no-store',
33
+ credentials: 'same-origin',
34
+ keepalive: true,
35
+ }).catch(() => {})
36
+ } catch (error) {
37
+ // 上报失败不影响页面
38
+ }
39
+ }
40
+
41
+ window.addEventListener('error', (event) => {
42
+ const target = event.target
43
+ if (target && target !== window && (target.src || target.href)) {
44
+ report({
45
+ kind: 'resource',
46
+ message: '资源加载失败',
47
+ url: String(target.src || target.href).slice(0, 200),
48
+ tag: target.tagName,
49
+ })
50
+ return
51
+ }
52
+ report({
53
+ kind: 'js-error',
54
+ message: String(event.message ?? '').slice(0, 300),
55
+ source: String(event.filename ?? '').slice(0, 200),
56
+ line: event.lineno ?? 0,
57
+ stack: event.error && event.error.stack ? String(event.error.stack).slice(0, 800) : '',
58
+ })
59
+ }, true)
60
+
61
+ window.addEventListener('unhandledrejection', (event) => {
62
+ const reason = event.reason
63
+ report({
64
+ kind: 'promise',
65
+ message: String((reason && (reason.message || reason)) ?? '').slice(0, 300),
66
+ stack: reason && reason.stack ? String(reason.stack).slice(0, 800) : '',
67
+ })
68
+ })
69
+
70
+ // 只拦 error / warn,每级 2 条:足够定位插件初始化失败,又不影响性能
71
+ for (const level of ['error', 'warn']) {
72
+ const original = console[level]
73
+ if (typeof original !== 'function') continue
74
+ let reported = 0
75
+ console[level] = function patched(...args) {
76
+ try {
77
+ if (reported < 2) {
78
+ reported += 1
79
+ report({
80
+ kind: 'console-' + level,
81
+ message: args.map((arg) => {
82
+ if (typeof arg === 'string') return arg
83
+ if (arg instanceof Error) return arg.message
84
+ try { return JSON.stringify(arg) } catch { return String(arg) }
85
+ }).join(' ').slice(0, 400),
86
+ })
87
+ }
88
+ } catch (error) { /* 忽略 */ }
89
+ return original.apply(console, args)
90
+ }
91
+ }
92
+
93
+ // 12 秒后检查应用是否挂载:仍在启动页或 #root 为空,
94
+ // 先自动换一个带随机参数的 URL 重载一次(破解缓存壳/浏览器进程中的旧状态),
95
+ // 再不行才显示自救提示。
96
+ setTimeout(() => {
97
+ try {
98
+ const root = document.getElementById('root')
99
+ const splash = document.querySelector('[data-dsh-boot]')
100
+ const mounted = Boolean(root && root.childElementCount > 0) && !splash
101
+ if (mounted) return
102
+ report({
103
+ kind: 'boot-timeout',
104
+ message: String(document.body?.innerText ?? '').replace(/\s+/g, ' ').slice(0, 400) || '(页面无文字)',
105
+ rootExists: Boolean(root),
106
+ splashPresent: Boolean(splash),
107
+ readyState: document.readyState,
108
+ })
109
+
110
+ // 自动重载:每次会话只尝试一次,避免死循环
111
+ let tried = false
112
+ try {
113
+ tried = sessionStorage.getItem('dsh-homing-boot-retry') === '1'
114
+ if (!tried) sessionStorage.setItem('dsh-homing-boot-retry', '1')
115
+ } catch (error) {
116
+ tried = true // 拿不到 sessionStorage 就不要再自动刷新
117
+ }
118
+ if (!tried) {
119
+ const url = new URL(location.href)
120
+ url.searchParams.set('_r', Date.now().toString(36))
121
+ location.replace(url.href)
122
+ return
123
+ }
124
+
125
+ showStuckOverlay()
126
+ } catch (error) {
127
+ // 忽略
128
+ }
129
+ }, 12000)
130
+
131
+ /**
132
+ * 启动卡住时给出可见的自救提示。
133
+ *
134
+ * 为什么需要(2026-11-15 实测):手机浏览器进程会积累坏状态(泄漏的 IndexedDB 连接等),
135
+ * 表现就是界面永远停在 "Loading plugins…",而**刷新、重开标签都没用**,
136
+ * 必须把浏览器从后台彻底关掉再打开才恢复。用户当时试了很多次都不知道这一点,
137
+ * 所以卡住时直接把这句话显示出来,配一个重新加载按钮。
138
+ */
139
+ function showStuckOverlay() {
140
+ if (document.getElementById('dsh-homing-stuck')) return
141
+ const box = document.createElement('div')
142
+ box.id = 'dsh-homing-stuck'
143
+ box.style.cssText = 'position:fixed;inset:auto 12px 12px 12px;z-index:2147483647;'
144
+ + 'background:#171a21;color:#e8eaed;border:1px solid #7a5a2c;border-radius:12px;'
145
+ + 'padding:14px;font:14px/1.6 system-ui,-apple-system,"Noto Sans SC",sans-serif;'
146
+ + 'box-shadow:0 8px 28px rgba(0,0,0,.5)'
147
+ const title = document.createElement('div')
148
+ title.textContent = 'DSH 启动卡住了'
149
+ title.style.cssText = 'font-weight:700;margin-bottom:6px'
150
+ const hint = document.createElement('div')
151
+ hint.style.cssText = 'color:#b7bec9;margin-bottom:10px'
152
+ hint.textContent = '请在手机的多任务里把这个浏览器彻底关掉(不是切后台),再重新打开。'
153
+ + '今天多次刷新都无效、只有彻底关掉浏览器才恢复,原因通常是浏览器进程里的旧状态没被清掉。'
154
+ const row = document.createElement('div')
155
+ row.style.cssText = 'display:flex;gap:8px'
156
+ const reload = document.createElement('button')
157
+ reload.textContent = '重新加载'
158
+ reload.style.cssText = 'flex:1;padding:10px;border:0;border-radius:8px;background:#4f7cff;color:#fff;font-weight:600'
159
+ reload.addEventListener('click', () => location.reload())
160
+ const diag = document.createElement('a')
161
+ diag.textContent = '诊断'
162
+ diag.href = '/dsh_homing/netdiag'
163
+ diag.style.cssText = 'flex:0 0 auto;padding:10px 14px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;text-align:center'
164
+ row.append(reload, diag)
165
+ box.append(title, hint, row)
166
+ document.body.appendChild(box)
167
+ }
168
+ })()
package/lib/compress.mjs CHANGED
@@ -134,14 +134,15 @@ function run(bin, args, { cwd, timeoutMs }) {
134
134
  /**
135
135
  * 把 target(文件或目录)压缩成加密归档,放在同级目录。
136
136
  * 返回 { ok, path, bytes, tool, strength, error }
137
+ * @param {{ target: string, password: string, timeoutMs?: number, backends?: Array }} options
138
+ * backends 默认按本机探测结果;显式传入只为测试可控(不改生产行为)
137
139
  */
138
- export function createEncryptedArchive({ target, password, timeoutMs = 10 * 60_000 }) {
140
+ export function createEncryptedArchive({ target, password, timeoutMs = 10 * 60_000, backends = availableBackends() }) {
139
141
  const passwordError = checkPassword(password)
140
142
  if (passwordError) return { ok: false, error: passwordError }
141
143
  if (typeof target !== 'string' || target.trim() === '') return { ok: false, error: '路径为空' }
142
144
  if (!fs.existsSync(target)) return { ok: false, error: '目标不存在' }
143
145
 
144
- const backends = availableBackends()
145
146
  if (backends.length === 0) {
146
147
  return {
147
148
  ok: false,
@@ -0,0 +1,150 @@
1
+ /**
2
+ * 调试页的上传脚本(外部文件,不是内联脚本)。
3
+ *
4
+ * 为什么必须放在外部文件里(2026-11-15 事故):
5
+ * 页面响应头带 `Content-Security-Policy: ... script-src 'self'`,没有 'unsafe-inline'。
6
+ * 所以写在 HTML 里的 <script>…</script> 会被浏览器直接丢弃——按钮没有监听器,
7
+ * 点了完全没反应,连请求都不会发出(审计日志里一条记录都没有)。
8
+ * 改成同源外部脚本(script-src 'self' 允许)后才会真正执行。
9
+ *
10
+ * 逻辑:
11
+ * 1. 选图后先在本机压缩(长边 ≤1600 / JPEG 0.85),手机 4K 截图从几 MB 降到几百 KB
12
+ * 2. 用 dataURL 交给 /debug/upload,服务端落盘到 debug/shots/
13
+ * 3. 每一步都给可见回执:读取中 / 上传中(XKB) / 已保存(XKB·Yms) / 失败(HTTP 状态+原因)
14
+ * 4. 30 秒超时兜底,上传期间禁用按钮防重复点击
15
+ */
16
+ (() => {
17
+ const input = document.getElementById('file')
18
+ const button = document.getElementById('send')
19
+ const result = document.getElementById('result')
20
+ if (!input || !button || !result) return
21
+
22
+ const MAX_EDGE = 1600
23
+ const MAX_BYTES = 12 * 1024 * 1024
24
+ const TIMEOUT_MS = 30000
25
+
26
+ const info = (message) => {
27
+ result.className = 'sub'
28
+ result.textContent = message
29
+ }
30
+ const fail = (message) => {
31
+ result.className = 'sub err'
32
+ result.textContent = '失败:' + message
33
+ }
34
+
35
+ /** 缩到长边 1600 的 JPEG;失败就退回原图(宁可能传,也别因为压缩失败卡住) */
36
+ function shrink(file) {
37
+ return new Promise((resolve) => {
38
+ const reader = new FileReader()
39
+ reader.onerror = () => resolve(null)
40
+ reader.onload = () => {
41
+ const original = String(reader.result)
42
+ const image = new Image()
43
+ image.onerror = () => resolve(original)
44
+ image.onload = () => {
45
+ try {
46
+ const longest = Math.max(image.width, image.height)
47
+ const scale = Math.min(1, MAX_EDGE / longest)
48
+ if (scale === 1 && file.size <= 1.5 * 1024 * 1024) {
49
+ resolve(original)
50
+ return
51
+ }
52
+ const canvas = document.createElement('canvas')
53
+ canvas.width = Math.max(1, Math.round(image.width * scale))
54
+ canvas.height = Math.max(1, Math.round(image.height * scale))
55
+ const context = canvas.getContext('2d')
56
+ if (!context) {
57
+ resolve(original)
58
+ return
59
+ }
60
+ context.drawImage(image, 0, 0, canvas.width, canvas.height)
61
+ resolve(canvas.toDataURL('image/jpeg', 0.85))
62
+ } catch (error) {
63
+ resolve(original)
64
+ }
65
+ }
66
+ image.src = original
67
+ }
68
+ reader.readAsDataURL(file)
69
+ })
70
+ }
71
+
72
+ button.addEventListener('click', async () => {
73
+ const file = input.files && input.files[0]
74
+ if (!file) {
75
+ fail('先选一张图片。')
76
+ return
77
+ }
78
+ if (file.size > MAX_BYTES) {
79
+ fail('图片太大(上限 12MB)。')
80
+ return
81
+ }
82
+
83
+ button.disabled = true
84
+ const startedAt = Date.now()
85
+ try {
86
+ info('读取中…')
87
+ const dataUrl = await shrink(file)
88
+ if (!dataUrl) {
89
+ fail('这个文件读不出来,换一张试试(或重新截一次图)。')
90
+ return
91
+ }
92
+ const kb = Math.round((dataUrl.length * 3) / 4 / 1024)
93
+ info('上传中…(' + kb + 'KB)')
94
+
95
+ const controller = new AbortController()
96
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
97
+ let response
98
+ try {
99
+ response = await fetch(location.pathname.replace(/\/$/u, '') + '/upload', {
100
+ method: 'POST',
101
+ headers: { 'content-type': 'application/json' },
102
+ body: JSON.stringify({ name: file.name, dataUrl }),
103
+ signal: controller.signal,
104
+ })
105
+ } catch (error) {
106
+ const aborted = error && (error.name === 'AbortError' || error.name === 'TimeoutError')
107
+ if (aborted) fail('等了 30 秒没有响应(已传 ' + kb + 'KB),可能是隧道/反代截断了请求体。')
108
+ else fail('请求没发出去或连接被断开(' + (error && error.message ? error.message : error) + ',' + kb + 'KB)。')
109
+ return
110
+ } finally {
111
+ clearTimeout(timer)
112
+ }
113
+
114
+ const text = await response.text()
115
+ const elapsed = Date.now() - startedAt
116
+ if (!response.ok) {
117
+ let reason = text.slice(0, 200)
118
+ try {
119
+ const parsedError = JSON.parse(text)
120
+ if (parsedError && parsedError.error) reason = parsedError.error
121
+ } catch (error) {
122
+ // 保留原文
123
+ }
124
+ fail('HTTP ' + response.status + ' · ' + reason + '(' + elapsed + 'ms)')
125
+ return
126
+ }
127
+
128
+ let data = null
129
+ try {
130
+ data = JSON.parse(text)
131
+ } catch (error) {
132
+ data = null
133
+ }
134
+ if (!data || !data.file) {
135
+ fail('服务端返回看不懂:' + text.slice(0, 160))
136
+ return
137
+ }
138
+
139
+ info('已保存:' + data.file + '(' + kb + 'KB / ' + elapsed + 'ms)')
140
+ const image = document.createElement('img')
141
+ image.src = location.pathname.replace(/\/$/u, '') + '/files/' + encodeURIComponent(data.file)
142
+ image.style.cssText = 'width:88px;height:88px;object-fit:cover;border-radius:8px;border:1px solid #262b36;margin-top:8px'
143
+ const gallery = document.querySelector('.shots')
144
+ if (gallery) gallery.appendChild(image)
145
+ else result.appendChild(image)
146
+ } finally {
147
+ button.disabled = false
148
+ }
149
+ })
150
+ })()
package/lib/exec-path.mjs CHANGED
@@ -11,7 +11,15 @@
11
11
  import fs from 'node:fs'
12
12
  import path from 'node:path'
13
13
 
14
- const SYSTEM_ROOT = process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows'
14
+ /**
15
+ * Windows 系统目录:SystemRoot 优先,其次 WINDIR,最后回退 C:\Windows。
16
+ * 单独成函数便于测试三种取值(真实 Windows 上 SystemRoot 总是存在)。
17
+ */
18
+ export function systemRoot(env = process.env) {
19
+ return env.SystemRoot ?? env.WINDIR ?? 'C:\\Windows'
20
+ }
21
+
22
+ const SYSTEM_ROOT = systemRoot()
15
23
 
16
24
  function firstExisting(candidates, fallback) {
17
25
  for (const candidate of candidates) {
@@ -271,7 +271,7 @@ export function renderListing({ info, message, isError, home, dataDir, workspace
271
271
  ${entry.dir || !TEXT_FILE_RE.test(entry.name) ? '' : `<a class="mi" role="menuitem" data-act="edit" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u270F\uFE0F</span>编辑</a>`}
272
272
  ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="openpc" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F5A5}\uFE0F</span>在电脑打开</a>`}
273
273
  ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="download" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u2B07\uFE0F</span>下载</a>`}
274
- ${/\\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name) ? `<a class="mi" role="menuitem" data-act="preview" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F441}\uFE0F</span>预览</a>` : ''}
274
+ ${/\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name) ? `<a class="mi" role="menuitem" data-act="preview" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F441}\uFE0F</span>预览</a>` : ''}
275
275
  <a class="mi" role="menuitem" data-act="compress" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F512}</span>加密压缩</a>
276
276
  ${entry.runnable ? `<a class="mi" role="menuitem" data-act="run" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u25B6\uFE0F</span>执行</a>` : ''}
277
277
  <a class="mi" role="menuitem" data-act="rename" data-path="${escapeHtml(entry.path)}" data-name="${escapeHtml(entry.name)}" href="#"><span class="ico">\u{1F3F7}\uFE0F</span>重命名</a>
@@ -288,7 +288,7 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
288
288
  const rows = info.entries.map((entry) => {
289
289
  const label = escapeHtml(entry.name);
290
290
  const icon = entry.dir ? '\u{1F4C1}' : (entry.runnable ? '\u2699\uFE0F' : '\u{1F4C4}');
291
- const previewable = /\\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name)
291
+ const previewable = /\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name)
292
292
  const nameHtml = entry.dir
293
293
  ? `<a class="fname dir" href="/files?path=${encodeURIComponent(entry.path)}">${label}</a>`
294
294
  : previewable
@@ -434,7 +434,7 @@ export function renderFile({ info, message, isError, rendered = null }) {
434
434
  : '')
435
435
  const body = `
436
436
  <div class="bar">
437
- <h1>${escapeHtml(info.path.split(/[\\/]/u).pop() ?? info.path)}</h1>
437
+ <h1>${escapeHtml(info.path.split(/[\\/]/u).pop())}</h1>
438
438
  <div class="path">${escapeHtml(info.path)}</div>
439
439
  ${toggle}
440
440
  </div>
package/lib/files.mjs CHANGED
@@ -348,14 +348,13 @@ export function writeTextFile(absPath, text, limit = MAX_READ) {
348
348
 
349
349
  /** 判断命令是否可用(跨平台:Windows 查 where,其他查 PATH) */
350
350
  function commandExists(name) {
351
- try {
352
- const checker = process.platform === 'win32' ? systemExe('where') : systemExe('sh');
353
- const args = process.platform === 'win32' ? [name] : ['-c', 'command -v ' + JSON.stringify(name)];
354
- const out = spawnSync(checker, args, { encoding: 'utf8', windowsHide: true, timeout: 4000 });
355
- return out.status === 0 && String(out.stdout ?? '').trim().length > 0;
356
- } catch {
357
- return false;
358
- }
351
+ const isWindows = process.platform === 'win32';
352
+ const checker = isWindows ? systemExe('where') : systemExe('sh');
353
+ const args = isWindows ? [name] : ['-c', 'command -v ' + JSON.stringify(name)];
354
+ const out = spawnSync(checker, args, { encoding: 'utf8', windowsHide: true, timeout: 4000 });
355
+ // where / command -v 只有在找到命令时才以 0 退出(且 stdout 必有路径),
356
+ // spawnSync 对本函数的固定入参不会抛错,所以 status 就是唯一判据。
357
+ return out.status === 0;
359
358
  }
360
359
 
361
360
  /** 按类型执行文件,收集输出。不经过 shell 拼接(bat/ps1/sh 由解释器接手)。 */
@@ -454,13 +453,13 @@ export function runFile(absPath, args = '', { timeoutMs = 15_000, cwd } = {}) {
454
453
  };
455
454
 
456
455
  const timer = setTimeout(() => {
457
- try {
458
- if (process.platform === 'win32' && child.pid) {
459
- spawn(systemExe('taskkill'), ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
460
- } else {
461
- child.kill('SIGKILL');
462
- }
463
- } catch { /* 已退出 */ }
456
+ // 能走到这里说明子进程已成功拉起(pid 一定存在;拉起失败时 error 事件先于定时器触发)。
457
+ // Windows 用 taskkill 结束整棵进程树,其他平台发 SIGKILL;对已退出的子进程 kill 返回 false 而不抛错。
458
+ if (process.platform === 'win32') {
459
+ spawn(systemExe('taskkill'), ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
460
+ } else {
461
+ child.kill('SIGKILL');
462
+ }
464
463
  finish({ ok: true, code: null, output: decode(), truncated, timedOut: true });
465
464
  }, timeoutMs);
466
465
 
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 「距今多少秒」的显示文案。
3
+ *
4
+ * 背景:重启页原来直接拼 `30.6 秒前`,前面没有任何标签,放在红色列表里
5
+ * 会被读成「已经繁忙了 30.6 秒」。用户反馈看不懂,所以统一成带语义的短语,
6
+ * 由调用方补「最后活动」这类前缀。
7
+ *
8
+ * 浏览器端(restart/client.mjs)有一份等价的实现(那边不能 import ESM),
9
+ * 两边行为由 test/unit.format-age.test.mjs 的一致性用例守住。
10
+ */
11
+
12
+ /**
13
+ * @param {number} seconds 距今秒数(可以是小数)
14
+ * @returns {string} 例:'刚刚' / '30.6 秒前' / '2 分 5 秒前' / '1 小时 3 分前'
15
+ */
16
+ export function formatAge(seconds) {
17
+ const value = Number(seconds)
18
+ if (!Number.isFinite(value) || value < 0) return '未知'
19
+ if (value < 1) return '刚刚'
20
+ if (value < 60) return (Math.round(value * 10) / 10) + ' 秒前'
21
+ if (value < 3600) {
22
+ let minutes = Math.floor(value / 60)
23
+ let rest = Math.round(value % 60)
24
+ // 59.6 秒会被四舍五入成 60,必须进位,否则出现「1 分 60 秒前」
25
+ if (rest === 60) { minutes += 1; rest = 0 }
26
+ return rest === 0 ? (minutes + ' 分钟前') : (minutes + ' 分 ' + rest + ' 秒前')
27
+ }
28
+ const hours = Math.floor(value / 3600)
29
+ let minutes = Math.round((value % 3600) / 60)
30
+ if (minutes === 60) return ((hours + 1) + ' 小时前')
31
+ return minutes === 0 ? (hours + ' 小时前') : (hours + ' 小时 ' + minutes + ' 分前')
32
+ }
package/lib/git.mjs CHANGED
@@ -17,6 +17,18 @@ const GIT_EXE = gitExe()
17
17
  const TASKKILL = systemExe('taskkill')
18
18
  const MAX_OUTPUT = 64 * 1024
19
19
  const DEFAULT_TIMEOUT = 20_000
20
+ /** runGit 对"成功但没有任何输出"的占位符(页面直接展示时比空白友好) */
21
+ export const EMPTY_OUTPUT = '(无输出)'
22
+
23
+ /**
24
+ * 把输出里的占位符归一成空串:仓库概况字段不应该显示占位符。
25
+ * 调用点都先判 `result.ok`,而 runGit 成功(ok=true)时 output 必为字符串
26
+ * (close/timeout 分支都显式赋值),所以这里不需要 null/undefined 兜底。
27
+ */
28
+ const plainOutput = (value) => {
29
+ const text = String(value).trim()
30
+ return text === EMPTY_OUTPUT ? '' : text
31
+ }
20
32
 
21
33
  /** 是不是一个 git 仓库的根目录(有 .git 目录或 gitfile) */
22
34
  export function isRepo(dir) {
@@ -36,14 +48,21 @@ export async function repoSummary(dir) {
36
48
  runGit(dir, ['log', '-1', '--pretty=%h %ad %s', '--date=format:%m-%d %H:%M']),
37
49
  runGit(dir, ['branch', '-a', '--format=%(refname:short)']),
38
50
  ])
39
- const dirty = status.ok ? status.output.trim().split('\n').filter(Boolean) : []
51
+ // 注意:runGit 成功且无输出时会返回占位符,这里必须先归一成空串,
52
+ // 否则干净仓库会被算成"有 1 个脏文件"、无远端会被显示成"(无输出)"。
53
+ const statusText = status.ok ? plainOutput(status.output) : ''
54
+ const dirty = statusText === '' ? [] : statusText.split('\n').filter(Boolean)
55
+ const remoteText = remote.ok ? plainOutput(remote.output) : ''
40
56
  return {
41
- branch: branch.ok ? branch.output.trim() : '',
57
+ branch: branch.ok ? plainOutput(branch.output) : '',
42
58
  dirty,
43
- remote: remote.ok ? remote.output.trim().split('\n')[0] ?? '' : '',
44
- last: last.ok ? last.output.trim() : '',
59
+ remote: remoteText === '' ? '' : remoteText.split('\n')[0],
60
+ last: last.ok ? plainOutput(last.output) : '',
45
61
  branches: branches.ok
46
- ? branches.output.split('\n').map((line) => line.trim()).filter((line) => line !== '' && !line.includes('HEAD'))
62
+ ? plainOutput(branches.output)
63
+ .split('\n')
64
+ .map((line) => line.trim())
65
+ .filter((line) => line !== '' && !line.includes('HEAD'))
47
66
  : [],
48
67
  }
49
68
  }
@@ -90,25 +109,24 @@ export function runGit(cwd, args, { timeoutMs = DEFAULT_TIMEOUT } = {}) {
90
109
  child.stderr.on('data', collect)
91
110
 
92
111
  const decode = () => {
93
- // git 的输出基本都是 ASCII/UTF-8;路径在这种环境下也很少出现 GBK
112
+ // git 的输出基本都是 ASCII/UTF-8;路径在这种环境下也很少出现 GBK。
113
+ // DSH 自带运行时是 full ICU(已核实 small-icu: false),TextDecoder('gbk') 必然可用,
114
+ // 所以这里不需要 try/catch 兜底(少一个永不可达的分支)。
94
115
  const buffer = Buffer.concat(chunks).subarray(0, MAX_OUTPUT)
95
116
  const utf8 = buffer.toString('utf8')
96
117
  if (!utf8.includes('\uFFFD')) return utf8
97
- try {
98
- return new TextDecoder('gbk').decode(buffer)
99
- } catch {
100
- return utf8
101
- }
118
+ return new TextDecoder('gbk').decode(buffer)
102
119
  }
103
120
 
104
121
  const timer = setTimeout(() => {
105
- try {
106
- if (process.platform === 'win32' && child.pid) {
107
- spawn(TASKKILL, ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
108
- } else {
109
- child.kill('SIGKILL')
110
- }
111
- } catch { /* 已退出 */ }
122
+ // 超时终止:Windows 用 taskkill 结束整个进程树(git 会派生子进程),
123
+ // 其它平台直接 SIGKILL。参数都是静态字符串、TASKKILL 是绝对路径,
124
+ // spawn 既不会同步抛错也不会异步失败(置为 ignore 的 stdio 也不会回传输出)。
125
+ if (process.platform === 'win32') {
126
+ spawn(TASKKILL, ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
127
+ } else {
128
+ child.kill('SIGKILL')
129
+ }
112
130
  finish({ ok: false, timeout: true, code: null, output: decode() + '\n(超时,已终止)' })
113
131
  }, timeoutMs)
114
132
 
@@ -119,7 +137,7 @@ export function runGit(cwd, args, { timeoutMs = DEFAULT_TIMEOUT } = {}) {
119
137
  child.on('close', (code) => {
120
138
  clearTimeout(timer)
121
139
  const output = decode()
122
- finish({ ok: code === 0, code, output: output === '' ? '(无输出)' : output })
140
+ finish({ ok: code === 0, code, output: output === '' ? EMPTY_OUTPUT : output })
123
141
  })
124
142
  })
125
143
  }