lantern-harness 0.1.6 → 0.1.7

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 (91) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +1 -1
  3. package/builtin/session/update-check.mjs +517 -0
  4. package/cli/lantern.mjs +123 -22
  5. package/cli/server.mjs +5 -2
  6. package/dist/500.html +3 -3
  7. package/dist/_astro/Base.Bum3N3jp.css +1 -0
  8. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.D0snmAJ_.js +1 -0
  9. package/dist/_astro/{CaseExecBoard.FJ1Y9b4e.js → CaseExecBoard.BAV4EE3o.js} +1 -1
  10. package/dist/_astro/{CaseGenerateApp.CT2n4VOf.js → CaseGenerateApp.Bz4ryNJG.js} +1 -1
  11. package/dist/_astro/{CasesLibrary.BjrehOiI.js → CasesLibrary.BPifyHUA.js} +1 -1
  12. package/dist/_astro/{ChatApp.Dqfx4FcI.js → ChatApp.DLo31SYZ.js} +5 -5
  13. package/dist/_astro/{DashboardBoard.wILBO_CD.js → DashboardBoard.DtuJX0Oi.js} +2 -2
  14. package/dist/_astro/{DocsFileBrowser.D32MgVAR.js → DocsFileBrowser.D3cKurQE.js} +1 -1
  15. package/dist/_astro/{DocsPager.BARD7JvD.js → DocsPager.rzu4mnzw.js} +1 -1
  16. package/dist/_astro/{KnowledgeLibrary.C-Sg2R6B.js → KnowledgeLibrary.B0sO4QR1.js} +1 -1
  17. package/dist/_astro/{NavLibraries.BzInZVDf.js → NavLibraries.Cvg3wery.js} +1 -1
  18. package/dist/_astro/{PluginsPage.CVyua_fb.js → PluginsPage.DIltPILi.js} +2 -2
  19. package/dist/_astro/PluginsPage.uvmSuXzi.js +1 -0
  20. package/dist/_astro/PmBugsBoard.CiaIhCHv.js +1 -0
  21. package/dist/_astro/PmIterationsBoard.H67QwKFw.js +1 -0
  22. package/dist/_astro/{PmProjectDetail.CtQdpGes.js → PmProjectDetail.DqDoIg8a.js} +1 -1
  23. package/dist/_astro/PmProjectsBoard.nOC1Hugt.js +1 -0
  24. package/dist/_astro/PmRequirementsBoard.BPjZ7khP.js +1 -0
  25. package/dist/_astro/PmRequirementsBoard.CanxvcKg.js +1 -0
  26. package/dist/_astro/PmShared.CZnXaUq-.js +1 -0
  27. package/dist/_astro/{PromptsLibrary.Z1DQBrFL.js → PromptsLibrary.DU9EuSim.js} +1 -1
  28. package/dist/_astro/{ReportsPage.CGpIPPr9.js → ReportsPage.Cr88iz8c.js} +1 -1
  29. package/dist/_astro/{RequirementsLibrary.D8078xLd.js → RequirementsLibrary.BwriF8F0.js} +1 -1
  30. package/dist/_astro/{SearchableSelect.BTJoZC_a.js → SearchableSelect.Ctg8V1Z1.js} +1 -1
  31. package/dist/_astro/SettingsDialog.kpJwoEl3.js +1 -0
  32. package/dist/_astro/SpaceSwitcher.BEJo5KFi.js +7 -0
  33. package/dist/_astro/{TasksBoard.CL-sNPZN.js → TasksBoard.BZi_GBPG.js} +1 -1
  34. package/dist/_astro/{TemplatesLibrary.d6uIe7I-.js → TemplatesLibrary.T4K9jUex.js} +1 -1
  35. package/dist/_astro/{TestStatsBoard.CSdXWc4Q.js → TestStatsBoard.Dd1Kcmx6.js} +1 -1
  36. package/dist/_astro/{TodosBoard.nl23X5Gi.js → TodosBoard.C4yd_JFb.js} +1 -1
  37. package/dist/_astro/app-config.DKMxjv3g.js +1 -0
  38. package/dist/_astro/i18n.BXeGGutk.js +7 -0
  39. package/dist/_astro/{open-docs-in-session.B5cUxqHi.js → open-docs-in-session.B0ZdZNj2.js} +1 -1
  40. package/dist/_astro/{plugins.DaDJq-mn.js → plugins.D5ypJIXn.js} +1 -1
  41. package/dist/_astro/pm.BsnTv63L.js +4 -0
  42. package/dist/_astro/{settings.CMK4PEak.js → settings.CnDCvwnQ.js} +2 -2
  43. package/dist/_astro/{spaces-client.CoQfaOIO.js → spaces-client.Cai2tHEI.js} +1 -1
  44. package/dist/_astro/update.DXCPfU4a.js +1 -0
  45. package/dist/_astro/{view-prefs.Dhdh8Z5a.js → view-prefs.HCowOWXL.js} +1 -1
  46. package/dist/case-exec/index.html +4 -4
  47. package/dist/cases/generate/index.html +4 -4
  48. package/dist/cases/library/index.html +4 -4
  49. package/dist/dashboard/index.html +4 -4
  50. package/dist/docs/changelog/index.html +18 -4
  51. package/dist/docs/install/index.html +3 -3
  52. package/dist/docs/manual/index.html +15 -5
  53. package/dist/index.html +4 -4
  54. package/dist/knowledge/index.html +4 -4
  55. package/dist/knowledge//345/212/237/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/347/274/226/345/206/231/350/247/204/350/214/203/index.html +3 -3
  56. package/dist/plugins/index.html +4 -4
  57. package/dist/pm/bugs/index.html +4 -4
  58. package/dist/pm/iterations/index.html +4 -4
  59. package/dist/pm/projects/detail/index.html +4 -4
  60. package/dist/pm/projects/index.html +4 -4
  61. package/dist/pm/requirements/index.html +4 -4
  62. package/dist/prompts/index.html +4 -4
  63. package/dist/reports/index.html +4 -4
  64. package/dist/requirements/index.html +4 -4
  65. package/dist/tasks/index.html +4 -4
  66. package/dist/templates/index.html +4 -4
  67. package/dist/templates//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +3 -3
  68. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +3 -3
  69. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +3 -3
  70. package/dist/templates//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +3 -3
  71. package/dist/templates//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +3 -3
  72. package/dist/test-stats/index.html +4 -4
  73. package/dist/todos/index.html +4 -4
  74. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +13 -2
  75. package/lh-plugins/lh-pm.mjs +18 -4
  76. package/lh-plugins/lh-update.mjs +171 -0
  77. package/package.json +1 -1
  78. package/dist/_astro/Base.DGaLtzMo.css +0 -1
  79. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.uhTNjhRY.js +0 -1
  80. package/dist/_astro/PluginsPage.CS1GaJtR.js +0 -1
  81. package/dist/_astro/PmBugsBoard.BXUu0kNL.js +0 -1
  82. package/dist/_astro/PmIterationsBoard.Deso1uyK.js +0 -1
  83. package/dist/_astro/PmProjectsBoard.MM4vxneK.js +0 -1
  84. package/dist/_astro/PmRequirementsBoard.62ONLCH5.js +0 -1
  85. package/dist/_astro/PmRequirementsBoard.SLVDgspp.js +0 -1
  86. package/dist/_astro/PmShared.CwCmF-kI.js +0 -1
  87. package/dist/_astro/SettingsDialog.BA57gp90.js +0 -1
  88. package/dist/_astro/SpaceSwitcher.DZ8b_85M.js +0 -7
  89. package/dist/_astro/app-config.huKxSIlN.js +0 -1
  90. package/dist/_astro/i18n.Bbh04ngD.js +0 -7
  91. package/dist/_astro/pm.CpFmMslU.js +0 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # 版本日志
2
2
 
3
+ ## [0.1.7] - 2026-10-19
4
+
5
+ 应用内检查 npm 最新版本并一键更新:侧栏版本号旁提示新版本,设置页「平台版本」可检查、更新并自动重启,覆盖全局安装与 `npx` 两种运行方式;缺陷状态改为「待确认 / 待修复 / 修复完成 / 待验证 / 验证通过 / 已取消」。
6
+
7
+ ### 新增
8
+
9
+ - 应用内检查 npm 最新版本:侧栏版本号旁出现小圆点表示有新版本,点击打开「设置 → 通用 → 平台版本」,可手动检查、一键更新并自动重启(停服 → 全局安装 → 用原端口重启)。全局安装与 `npx` 两种运行方式都支持:`npx` 模式会先装到全局,再用全局 `lantern` 拉起,重启时保留原来的数据空间池根。源码 / dev 模式只提示,不执行更新
10
+ - 更新状态写到 `~/.config/lantern-harness/update-status.json`,新进程启动后继续报告进度;失败时保留错误与日志路径,旧版本会自动恢复启动
11
+ - 版本检查支持 HTTP(S) 代理:按环境变量 → npm 配置 → macOS 系统代理(`scutil --proxy`)的顺序探测(Node 自带的 `fetch` 不读系统代理,国内挂代理时直连 registry 会直接失败),探测到的代理同时传给 `npm/pnpm` 全局安装;都连不上时提示「无法连接 registry + 检查代理或换镜像」,而不是抛 `fetch failed`
12
+
13
+ ### 优化
14
+
15
+ - 缺陷状态改为 **待确认 / 待修复 / 修复完成 / 待验证 / 验证通过 / 已取消**:原来的「修复中」「已关闭」不再出现在下拉里——「修复中」并入「修复完成」,「已关闭」改为「验证通过」,并新增「已取消」;旧数据读取时自动转换(`in_progress` → `fixed`、`closed` → `passed`),不用手工改 JSON。项目详情的「缺陷关闭 %」随之改称「缺陷完成 %」(验证通过 + 已取消都算收尾)。AI 修改缺陷状态时仍只推进到「待验证」,验证通过与已取消由用户决定
16
+ - 需求 / 缺陷的附件图片改为页内预览:点缩略图或文件名直接在当前页放大,不再跳新标签,抽屉里也不会因为预览而丢掉正在编辑的内容
17
+ - 切换数据空间后,若新空间没有当前页面对应的插件菜单,自动回到工作台,不再停在一个「插件未启用」的提示页上
18
+
3
19
  ## [0.1.6] - 2026-10-19
4
20
 
5
21
  新增「项目管理」四个插件与配套 AI 工具;仪表盘改为 12 列自由画布;工作台的 AI 待办改成快卡确认并支持日期区间。
package/README.md CHANGED
@@ -28,7 +28,7 @@ AI 工作台:对话与插件工具、需求 / 用例 / 知识 / 提示词内
28
28
  npx lantern-harness
29
29
  ```
30
30
 
31
- 执行后会安装全局短命令 `lantern`,之后用 `lantern init` / `lantern web` 操作即可。升级用 `lantern update`(在跑的服务会自动停掉、装完重新拉起)。
31
+ 执行后会安装全局短命令 `lantern`,之后用 `lantern init` / `lantern web` 操作即可。升级有两种方式:终端执行 `lantern update`(在跑的服务会自动停掉、装完重新拉起),或在页面「设置 → 通用 → 平台版本」点「检查更新 / 更新并重启」——有新版本时侧栏版本号旁也会出现小圆点。`npx` 模式下的页面更新会先装到全局,再用全局 `lantern` 启动。
32
32
 
33
33
  2、 初始化数据空间(首次必做;可再次执行以更换数据空间):
34
34
 
@@ -0,0 +1,517 @@
1
+ /**
2
+ * 版本检测与更新状态的共享逻辑(本地服务插件 + CLI 共用)。
3
+ *
4
+ * 只做四件事,且都不改任何业务数据:
5
+ * 1. 版本号比较(段位数字,支持 `v` 前缀与预发布后缀)
6
+ * 2. 向 npm registry 查最新版本(30 分钟缓存,可强制刷新)
7
+ * 3. 判断当前包是怎么装的(npx / 全局 / 源码),以及全局安装位置
8
+ * 4. 读写「正在更新」状态文件,让重启后的新进程能接上未完成的升级
9
+ *
10
+ * 网络失败一律降级为 `error` 字段,不抛出:页面只是少一个更新标记,
11
+ * 不该因为公司网络连不上 registry 就报错。
12
+ */
13
+ import fs from 'node:fs';
14
+ import net from 'node:net';
15
+ import os from 'node:os';
16
+ import path from 'node:path';
17
+ import tls from 'node:tls';
18
+ import { spawnSync } from 'node:child_process';
19
+
20
+ import { getUserConfigDir } from '../../cli/user-config.mjs';
21
+
22
+ /** 最新版本缓存:同一进程内 30 分钟内不再打 registry */
23
+ export const CHECK_TTL_MS = 30 * 60 * 1000;
24
+ /** 状态文件里 `installing` 超过这个时间视为上一次升级中断 */
25
+ export const STATUS_STALE_MS = 10 * 60 * 1000;
26
+ const FETCH_TIMEOUT_MS = 4000;
27
+
28
+ const DEFAULT_REGISTRY = 'https://registry.npmjs.org/';
29
+
30
+ /* ---------------------------- 版本号 ---------------------------- */
31
+
32
+ /**
33
+ * 语义化版本比较:返回 -1 / 0 / 1。
34
+ * 只按数字段比较,预发布(`1.0.0-beta.1`)视为小于同段正式版;
35
+ * 段数不同按 0 补齐(`0.1` 等价 `0.1.0`)。
36
+ * @param {string} [a]
37
+ * @param {string} [b]
38
+ */
39
+ export function compareVersions(a, b) {
40
+ const parse = (raw) => {
41
+ const text = String(raw ?? '')
42
+ .trim()
43
+ .replace(/^[vV]/, '');
44
+ const [core, pre = ''] = text.split('-', 2);
45
+ const nums = core
46
+ .split('.')
47
+ .map((x) => Number.parseInt(x, 10))
48
+ .map((x) => (Number.isFinite(x) ? x : 0));
49
+ return { nums, pre: pre.trim() };
50
+ };
51
+ const left = parse(a);
52
+ const right = parse(b);
53
+ const len = Math.max(left.nums.length, right.nums.length);
54
+ for (let i = 0; i < len; i += 1) {
55
+ const x = left.nums[i] ?? 0;
56
+ const y = right.nums[i] ?? 0;
57
+ if (x !== y) return x > y ? 1 : -1;
58
+ }
59
+ // 正式版大于预发布:1.0.0 > 1.0.0-beta
60
+ if (!left.pre && right.pre) return 1;
61
+ if (left.pre && !right.pre) return -1;
62
+ if (left.pre === right.pre) return 0;
63
+ return left.pre > right.pre ? 1 : -1;
64
+ }
65
+
66
+ /** 是否有可用的新版本(本地版本更高或相等都算没有) */
67
+ export function hasUpdate(latest, current) {
68
+ if (!latest || !current) return false;
69
+ return compareVersions(latest, current) > 0;
70
+ }
71
+
72
+ /* ------------------------- 安装方式与包管理器 ------------------------- */
73
+
74
+ /** 进程内缓存:pnpm / npm 的检测要 spawn 子进程,没必要每次请求都跑 */
75
+ let packageManagerCache = '';
76
+
77
+ /**
78
+ * pnpm 是否「可用于全局安装」:既要有 pnpm,也要它的全局 bin 目录已在 PATH 上。
79
+ * 没执行过 pnpm setup 时 `pnpm add -g` 会直接报 ERR_PNPM_GLOBAL_BIN_DIR_NOT_IN_PATH,
80
+ * 此时退避到 npm,否则用户会装不上(npm 随 Node 一起安装,必然可用)。
81
+ */
82
+ export function isPnpmGlobalReady() {
83
+ const probe = spawnSync('pnpm', ['bin', '-g'], {
84
+ stdio: 'ignore',
85
+ shell: process.platform === 'win32',
86
+ });
87
+ return !probe.error && probe.status === 0;
88
+ }
89
+
90
+ /** 优先 pnpm(可直接用于全局安装时);否则回退 npm */
91
+ export function resolvePackageManager() {
92
+ // 每个页面加载都会问一次;缓存住,省掉重复 spawn pnpm 的开销
93
+ if (!packageManagerCache) {
94
+ packageManagerCache = isPnpmGlobalReady() ? 'pnpm' : 'npm';
95
+ }
96
+ return packageManagerCache;
97
+ }
98
+
99
+ function runCapture(cmd, args) {
100
+ const r = spawnSync(cmd, args, {
101
+ encoding: 'utf8',
102
+ shell: process.platform === 'win32',
103
+ });
104
+ if (r.error || r.status !== 0) return '';
105
+ return String(r.stdout ?? '').trim();
106
+ }
107
+
108
+ const globalRootCache = new Map();
109
+
110
+ /**
111
+ * 全局包的 node_modules 根目录;解析不到时返回空串。
112
+ * npm:`npm root -g`;pnpm:`pnpm root -g`。
113
+ * @param {string} pm
114
+ */
115
+ export function resolveGlobalRoot(pm) {
116
+ const key = pm || 'npm';
117
+ if (globalRootCache.has(key)) return globalRootCache.get(key);
118
+ const out =
119
+ key === 'pnpm' ? runCapture('pnpm', ['root', '-g']) : runCapture('npm', ['root', '-g']);
120
+ globalRootCache.set(key, out);
121
+ return out;
122
+ }
123
+
124
+ /**
125
+ * 全局安装的 `lantern` 可执行文件路径;找不到返回空串。
126
+ * npm:`npm prefix -g`(Windows 下可执行文件直接在 prefix 里,其它平台在 prefix/bin);
127
+ * pnpm:`pnpm bin -g` 本身就是 bin 目录。
128
+ * @param {string} pm
129
+ */
130
+ export function resolveGlobalCli(pm) {
131
+ const exe = process.platform === 'win32' ? 'lantern.cmd' : 'lantern';
132
+ let dir = '';
133
+ if (pm === 'pnpm') {
134
+ dir = runCapture('pnpm', ['bin', '-g']);
135
+ } else {
136
+ const prefix = runCapture('npm', ['prefix', '-g']);
137
+ if (prefix) dir = process.platform === 'win32' ? prefix : path.join(prefix, 'bin');
138
+ }
139
+ if (!dir) return '';
140
+ const candidate = path.join(dir, exe);
141
+ return fs.existsSync(candidate) ? candidate : '';
142
+ }
143
+
144
+ /**
145
+ * 判断当前进程读到的包是怎么装的:
146
+ * - `npx`:npx 临时缓存(`~/.npm/_npx/<hash>/node_modules/…`),装完不会自动替换
147
+ * - `global`:包目录位于全局 node_modules 下,可以直接全局替换
148
+ * - `dev`:仓库源码 / 其它本地安装,不能从页面里一键更新
149
+ * @param {string} pkgRoot 包根目录(含 package.json)
150
+ * @param {string} [pm] 不传则现算
151
+ * @param {string} [globalRootOverride] 测试注入的全局 node_modules 根
152
+ * @returns {'npx' | 'global' | 'dev'}
153
+ */
154
+ export function detectInstallMode(pkgRoot, pm, globalRootOverride) {
155
+ const abs = path.resolve(pkgRoot || '');
156
+ if (!abs) return 'dev';
157
+ if (abs.split(path.sep).includes('_npx')) return 'npx';
158
+ const root =
159
+ globalRootOverride === undefined
160
+ ? resolveGlobalRoot(pm || resolvePackageManager())
161
+ : globalRootOverride;
162
+ if (root && (abs === root || abs.startsWith(`${root}${path.sep}`))) return 'global';
163
+ // 解析不到全局根时退回结构判断;仍不确定就按源码处理(宁可只提示)
164
+ return 'dev';
165
+ }
166
+
167
+ /* ------------------------------ 代理 ------------------------------ */
168
+
169
+ /**
170
+ * 国内常见环境:系统挂了代理(Clash / Surge 等),浏览器能上 npm,
171
+ * 但 Node 的 fetch(undici)**不读系统代理,也不读 HTTP(S)_PROXY**(Node 22 及更早),
172
+ * 于是页面里的「检查更新」直接 `fetch failed`。
173
+ *
174
+ * 这里按顺序找代理:环境变量 → npm 配置 → macOS 系统代理(scutil)。
175
+ * 只支持 http(s) 代理;socks 需要额外代理进程,直接跳过并走直连。
176
+ */
177
+ const proxyCache = { resolved: false, url: '' };
178
+
179
+ /** @returns {string} 形如 `http://127.0.0.1:1082`,没有则空串 */
180
+ export function resolveProxyUrl() {
181
+ if (proxyCache.resolved) return proxyCache.url;
182
+ proxyCache.resolved = true;
183
+ const pick = (...names) => {
184
+ for (const name of names) {
185
+ const v = (process.env[name] || '').trim();
186
+ if (v) return v;
187
+ }
188
+ return '';
189
+ };
190
+ let candidate = pick(
191
+ 'HTTPS_PROXY',
192
+ 'https_proxy',
193
+ 'ALL_PROXY',
194
+ 'all_proxy',
195
+ 'HTTP_PROXY',
196
+ 'http_proxy',
197
+ );
198
+ if (!candidate) {
199
+ for (const key of ['https-proxy', 'proxy']) {
200
+ const raw = runCapture('npm', ['config', 'get', key]);
201
+ if (raw && /^https?:\/\//i.test(raw)) {
202
+ candidate = raw;
203
+ break;
204
+ }
205
+ }
206
+ }
207
+ if (!candidate && process.platform === 'darwin') {
208
+ // scutil --proxy 是 macOS 读系统代理的官方途径;输出是类似 plist 的键值对
209
+ const out = runCapture('scutil', ['--proxy']);
210
+ const on = /HTTPSEnable\s*:\s*1/.test(out);
211
+ const host = /HTTPSProxy\s*:\s*(\S+)/.exec(out)?.[1] ?? '';
212
+ const port = /HTTPSPort\s*:\s*(\d+)/.exec(out)?.[1] ?? '';
213
+ if (on && host && port) candidate = `http://${host}:${port}`;
214
+ }
215
+ // socks / pac 暂不支持:交给直连,失败时按网络问题提示
216
+ proxyCache.url = /^https?:\/\//i.test(candidate) ? candidate : '';
217
+ return proxyCache.url;
218
+ }
219
+
220
+ /** 给子进程(npm / pnpm 安装)补上代理环境变量;已有环境变量时不覆盖 */
221
+ export function proxyEnv() {
222
+ const url = resolveProxyUrl();
223
+ if (!url) return {};
224
+ const env = {};
225
+ if (!process.env.HTTPS_PROXY && !process.env.https_proxy) env.HTTPS_PROXY = url;
226
+ if (!process.env.HTTP_PROXY && !process.env.http_proxy) {
227
+ env.HTTP_PROXY = url;
228
+ env.http_proxy = url;
229
+ }
230
+ return env;
231
+ }
232
+
233
+ /**
234
+ * 走 HTTP 代理 CONNECT 隧道拿 HTTPS 响应,返回解析后的 JSON。
235
+ * 不引入 undici 依赖:包发布后 node_modules 布局不可控,内置模块最稳。
236
+ *
237
+ * 隧道建好后直接说 HTTP/1.1,而不是把 socket 交给 https.request:
238
+ * 后者会自己做 TLS/SNI 与 ALPN 协商,遇到只按 SNI 路由的本地代理容易握错证书。
239
+ */
240
+ function getJsonViaProxy(targetUrl, proxyUrl, timeoutMs) {
241
+ return new Promise((resolve, reject) => {
242
+ const target = new URL(targetUrl);
243
+ const proxy = new URL(proxyUrl);
244
+ const proxyPort = Number(proxy.port) || (proxy.protocol === 'https:' ? 443 : 80);
245
+ const targetPort = Number(target.port) || 443;
246
+ const targetPath = `${target.pathname}${target.search}`;
247
+
248
+ let settled = false;
249
+ let socket;
250
+ const finish = (err, value) => {
251
+ if (settled) return;
252
+ settled = true;
253
+ clearTimeout(timer);
254
+ socket?.destroy();
255
+ if (err) reject(err);
256
+ else resolve(value);
257
+ };
258
+ const timer = setTimeout(
259
+ () => finish(new Error(`代理连接超时(${proxy.host})`)),
260
+ Math.max(timeoutMs, 2000),
261
+ );
262
+
263
+ socket = net.connect({ host: proxy.hostname, port: proxyPort });
264
+ socket.on('error', (e) => finish(new Error(`代理连接失败:${e.message}`)));
265
+ socket.once('connect', () => {
266
+ const auth = proxy.username
267
+ ? `Proxy-Authorization: Basic ${Buffer.from(
268
+ `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`,
269
+ ).toString('base64')}\r\n`
270
+ : '';
271
+ socket.write(
272
+ `CONNECT ${target.hostname}:${targetPort} HTTP/1.1\r\n` +
273
+ `Host: ${target.hostname}:${targetPort}\r\n${auth}\r\n`,
274
+ );
275
+ });
276
+
277
+ // 阶段一:读 CONNECT 的响应头,多读到的字节要留给 TLS(这里通常没有)
278
+ let handshake = '';
279
+ const onHandshake = (chunk) => {
280
+ handshake += chunk.toString('latin1');
281
+ const end = handshake.indexOf('\r\n\r\n');
282
+ if (end === -1) return;
283
+ socket.removeListener('data', onHandshake);
284
+ const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(handshake)?.[1] ?? 0);
285
+ if (status !== 200) {
286
+ finish(new Error(`代理拒绝连接(HTTP ${status || '?'})`));
287
+ return;
288
+ }
289
+ const leftover = Buffer.from(handshake.slice(end + 4), 'latin1');
290
+ openTunnel(leftover);
291
+ };
292
+ socket.on('data', onHandshake);
293
+
294
+ // 阶段二:在隧道上做 TLS,再按 HTTP/1.1 取一次
295
+ function openTunnel(leftover) {
296
+ const secured = tls.connect({
297
+ socket,
298
+ servername: target.hostname,
299
+ ALPNProtocols: ['http/1.1'],
300
+ });
301
+ secured.on('error', (e) => finish(new Error(`TLS 失败:${e.message}`)));
302
+ secured.once('secureConnect', () => {
303
+ if (leftover.length) secured.unshift(leftover);
304
+ secured.write(
305
+ `GET ${targetPath} HTTP/1.1\r\nHost: ${target.hostname}\r\n` +
306
+ 'Accept: application/json\r\nConnection: close\r\n\r\n',
307
+ );
308
+ });
309
+ const chunks = [];
310
+ secured.on('data', (c) => chunks.push(c));
311
+ secured.on('end', () => {
312
+ try {
313
+ finish(null, parseHttpJson(Buffer.concat(chunks)));
314
+ } catch (e) {
315
+ finish(e instanceof Error ? e : new Error(String(e)));
316
+ }
317
+ });
318
+ }
319
+ });
320
+ }
321
+
322
+ /** 把完整的 HTTP/1.1 响应解析成 JSON(支持 chunked,忽略压缩) */
323
+ export function parseHttpJson(raw) {
324
+ const text = raw.toString('utf8');
325
+ const split = text.indexOf('\r\n\r\n');
326
+ if (split === -1) throw new Error('代理返回内容不完整');
327
+ const head = text.slice(0, split);
328
+ const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(head)?.[1] ?? 0);
329
+ if (status >= 400 || status === 0) throw new Error(`HTTP ${status || '?'}`);
330
+ let body = text.slice(split + 4);
331
+ if (/transfer-encoding:\s*chunked/i.test(head)) {
332
+ let out = '';
333
+ let rest = body;
334
+ while (rest.length) {
335
+ const eol = rest.indexOf('\r\n');
336
+ if (eol === -1) break;
337
+ const size = Number.parseInt(rest.slice(0, eol).trim(), 16);
338
+ if (!Number.isFinite(size) || size <= 0) break;
339
+ out += rest.slice(eol + 2, eol + 2 + size);
340
+ rest = rest.slice(eol + 2 + size + 2);
341
+ }
342
+ body = out;
343
+ }
344
+ try {
345
+ return JSON.parse(body);
346
+ } catch {
347
+ throw new Error('返回内容不是合法 JSON');
348
+ }
349
+ }
350
+
351
+ /** 直连拿 JSON(undici fetch),失败抛出原始错误 */
352
+ async function getJsonDirect(targetUrl, timeoutMs) {
353
+ const res = await fetch(targetUrl, {
354
+ signal: AbortSignal.timeout(timeoutMs),
355
+ headers: { accept: 'application/json' },
356
+ });
357
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
358
+ return res.json();
359
+ }
360
+
361
+ /* ---------------------------- registry ---------------------------- */
362
+
363
+ /** npm 配置的 registry,统一补上结尾斜杠;读不到用官方源 */
364
+ export function readRegistry() {
365
+ const raw = runCapture('npm', ['config', 'get', 'registry']);
366
+ if (!raw || raw === 'undefined' || raw === 'null' || !/^https?:\/\//i.test(raw)) {
367
+ return DEFAULT_REGISTRY;
368
+ }
369
+ return raw.endsWith('/') ? raw : `${raw}/`;
370
+ }
371
+
372
+ /** @type {{ latest: string, checkedAt: number, error: string, registry: string } | null} */
373
+ let latestCache = null;
374
+
375
+ /**
376
+ * 查最新版本。失败返回 `{ latest: '', error }`,不抛出。
377
+ * @param {{ force?: boolean }} [opts]
378
+ */
379
+ export async function fetchLatestVersion(opts = {}) {
380
+ const now = Date.now();
381
+ if (!opts.force && latestCache && now - latestCache.checkedAt < CHECK_TTL_MS) {
382
+ return { ...latestCache };
383
+ }
384
+ const registry = readRegistry();
385
+ const url = `${registry}${encodeURIComponent('lantern-harness')}/latest`;
386
+ try {
387
+ const proxy = resolveProxyUrl();
388
+ let data;
389
+ try {
390
+ // 有代理先走代理:Node 的 fetch 不认系统代理,直连在这类网络下必然失败
391
+ data = proxy
392
+ ? await getJsonViaProxy(url, proxy, FETCH_TIMEOUT_MS)
393
+ : await getJsonDirect(url, FETCH_TIMEOUT_MS);
394
+ } catch (proxied) {
395
+ if (!proxy) throw proxied;
396
+ // 代理坏了也别把「能直连」的网络堵死(比如代理已退出但系统设置还留着)
397
+ data = await getJsonDirect(url, FETCH_TIMEOUT_MS);
398
+ }
399
+ const latest = typeof data?.version === 'string' ? data.version.trim() : '';
400
+ if (!latest) throw new Error('返回内容缺少 version');
401
+ latestCache = { latest, checkedAt: now, error: '', registry };
402
+ } catch (e) {
403
+ const message = e instanceof Error ? e.message : String(e);
404
+ // `fetch failed` 对用户没有信息量:补一句该往哪查
405
+ const hint = /fetch failed|timeout|ENOTFOUND|ECONNREFUSED|timed out/i.test(message)
406
+ ? `无法连接 ${registry}(检查代理设置,或把 npm registry 换成可用镜像)`
407
+ : message;
408
+ latestCache = { latest: '', checkedAt: now, error: hint, registry };
409
+ }
410
+ return { ...latestCache };
411
+ }
412
+
413
+ /** 测试用:清掉版本缓存 */
414
+ export function __resetUpdateCheckCache() {
415
+ latestCache = null;
416
+ packageManagerCache = '';
417
+ globalRootCache.clear();
418
+ proxyCache.resolved = false;
419
+ proxyCache.url = '';
420
+ }
421
+
422
+ /* --------------------------- 更新状态文件 --------------------------- */
423
+
424
+ export function getUpdateStatusPath() {
425
+ return path.join(getUserConfigDir(), 'update-status.json');
426
+ }
427
+
428
+ /**
429
+ * 读上一次更新的状态。文件缺失 / 损坏都返回 null;
430
+ * `installing` 停留过久视为上次中断,标记为 failed,避免界面一直转圈。
431
+ */
432
+ export function readUpdateStatus() {
433
+ const file = getUpdateStatusPath();
434
+ try {
435
+ if (!fs.existsSync(file)) return null;
436
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
437
+ if (!raw || typeof raw !== 'object') return null;
438
+ const phase = String(raw.phase ?? '');
439
+ if (!['installing', 'restarting', 'done', 'failed'].includes(phase)) return null;
440
+ const status = {
441
+ phase,
442
+ from: String(raw.from ?? ''),
443
+ to: String(raw.to ?? ''),
444
+ startedAt: String(raw.startedAt ?? ''),
445
+ finishedAt: String(raw.finishedAt ?? ''),
446
+ error: String(raw.error ?? ''),
447
+ };
448
+ if (phase === 'installing' || phase === 'restarting') {
449
+ const started = Date.parse(status.startedAt);
450
+ if (Number.isFinite(started) && Date.now() - started > STATUS_STALE_MS) {
451
+ return {
452
+ ...status,
453
+ phase: 'failed',
454
+ error: status.error || '更新未完成(服务可能已中断),请重试或使用 lantern update',
455
+ };
456
+ }
457
+ }
458
+ return status;
459
+ } catch {
460
+ return null;
461
+ }
462
+ }
463
+
464
+ /**
465
+ * 写更新状态(先写临时文件再改名,避免读到半份 JSON)。
466
+ * @param {{ phase: 'installing' | 'restarting' | 'done' | 'failed', from?: string, to?: string, error?: string }} patch
467
+ */
468
+ export function writeUpdateStatus(patch) {
469
+ const prev = readUpdateStatus() ?? {
470
+ phase: 'installing',
471
+ from: '',
472
+ to: '',
473
+ startedAt: '',
474
+ finishedAt: '',
475
+ error: '',
476
+ };
477
+ const now = new Date().toISOString();
478
+ const next = {
479
+ phase: patch.phase,
480
+ from: patch.from ?? prev.from,
481
+ to: patch.to ?? prev.to,
482
+ // 开始新一轮时重置计时;done / failed 保留原开始时间
483
+ startedAt: patch.phase === 'installing' ? now : prev.startedAt || now,
484
+ finishedAt: patch.phase === 'done' || patch.phase === 'failed' ? now : '',
485
+ error: patch.error ?? '',
486
+ };
487
+ try {
488
+ const file = getUpdateStatusPath();
489
+ fs.mkdirSync(path.dirname(file), { recursive: true });
490
+ const tmp = `${file}.tmp`;
491
+ fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
492
+ fs.renameSync(tmp, file);
493
+ } catch {
494
+ // 状态文件写不了不影响更新本身
495
+ }
496
+ return next;
497
+ }
498
+
499
+ /** 清掉更新状态(例如用户已确认刷新) */
500
+ export function clearUpdateStatus() {
501
+ try {
502
+ const file = getUpdateStatusPath();
503
+ if (fs.existsSync(file)) fs.unlinkSync(file);
504
+ } catch {
505
+ // ignore
506
+ }
507
+ }
508
+
509
+ /** 更新日志里给用户看的路径 */
510
+ export function updateLogHint() {
511
+ return path.join(getUserConfigDir(), 'logs', 'server.log');
512
+ }
513
+
514
+ /** 平台无关的临时目录(detached 子进程的 cwd,避开要替换的包目录) */
515
+ export function detachedCwd() {
516
+ return os.tmpdir() || os.homedir();
517
+ }