dsh-config-sync-plugin 0.0.0-stage → 0.3.56

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.
@@ -0,0 +1,200 @@
1
+ // 修正会话日志头部的 cwd —— 跨机还原会话的必要一步。
2
+ //
3
+ // 背景:DSH 把会话存在 <home>\sessions\<编码目录名>\<会话>\session.v4.jsonl.zstd,
4
+ // 目录名由「工作区绝对路径」编码而来;同时会话文件第一行 header 里还存着 cwd。
5
+ // 换机器/换盘后目录名按本机路径重新编码,但文件里的 cwd 仍是源机路径,
6
+ // DSH 校验两者不一致 → 判定 corrupt session log → sessionController 起不来 →
7
+ // 工作区/会话列表全空、界面报 "web boot: 1 entry did not activate"。
8
+ //
9
+ // ⚠ 关键:这些 .zstd 是**追加写入的多帧文件**(一个事件一帧,几百上千帧),
10
+ // 而 Node 的 zstdDecompressSync / createZstdDecompress 都**只解第一帧**。
11
+ // 若按"解压全文 → 改 header → 整文件重新压缩"来做,第二帧起的内容会被全部丢掉
12
+ // (文件从 900 KB 缩成 200 字节,会话只剩一个空壳)。所以这里只重写第一帧:
13
+ // 用二分找出第一帧的结束偏移,替换该帧,后面的字节原样保留。
14
+ //
15
+ // 用法:node fix-session-cwd.mjs <spec.json> [结果输出文件]
16
+ // spec.json = { "home": "<DSH home>", "dirs": { "<编码目录名>": "<本机工作区路径>" } }
17
+ // 只改 header 的 cwd,正文一帧都不动;已正确则跳过(幂等)。
18
+ //
19
+ // 第三个参数是给「客户端自带 Electron 当 node 跑」(ELECTRON_RUN_AS_NODE=1)用的:
20
+ // Electron 是 GUI 子系统程序,stdout 抓不到,结果必须落到文件里由 PowerShell 读。
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import zlib from 'node:zlib';
25
+
26
+ const specPath = process.argv[2];
27
+ const outPath = process.argv[3] || '';
28
+ if (!specPath) {
29
+ console.error('用法:node fix-session-cwd.mjs <spec.json> [out.json]');
30
+ process.exit(2);
31
+ }
32
+ const emit = (obj) => {
33
+ const text = JSON.stringify(obj);
34
+ if (outPath) {
35
+ try { fs.writeFileSync(outPath, text, 'utf8'); } catch { console.log(text); }
36
+ } else {
37
+ console.log(text);
38
+ }
39
+ };
40
+ if (typeof zlib.zstdDecompressSync !== 'function' || typeof zlib.zstdCompressSync !== 'function') {
41
+ console.error(`当前 Node ${process.version} 不支持 zstd,无法修正会话头部`);
42
+ process.exit(2);
43
+ }
44
+
45
+ const spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));
46
+ const home = String(spec.home || '').replace(/\//g, '\\').replace(/\\+$/, '');
47
+ const dirs = spec.dirs || {};
48
+ const sessionsRoot = path.join(home, 'sessions');
49
+
50
+ const result = { fixed: 0, alreadyOk: 0, missing: 0, failed: [] };
51
+
52
+ /** 第一帧解出来的文本(多帧文件也只返回第一帧)。 */
53
+ function decodeFirstFrame(buf) {
54
+ return zlib.zstdDecompressSync(buf);
55
+ }
56
+
57
+ /** 首帧是否带 zstd content checksum(帧头描述符 FHD 的 bit2)。 */
58
+ function frameHasChecksum(buf) {
59
+ return buf.length > 4 && ((buf.readUInt8(4) >> 2) & 1) === 1;
60
+ }
61
+
62
+ const ZSTD_MAGIC = [0x28, 0xb5, 0x2f, 0xfd];
63
+ const isFrameMagic = (b, i) => b[i] === 0x28 && b[i + 1] === 0xb5 && b[i + 2] === 0x2f && b[i + 3] === 0xfd;
64
+
65
+ /**
66
+ * 第一帧的结束偏移(即下一帧的起点)。
67
+ * 二分得到的是「最小可解前缀」——解压器只要能出数据就返回成功,
68
+ * 所以带 content checksum 的帧会算短 4 字节(checksum 那段被当成可省)。
69
+ * 不算这 4 字节就会把旧 checksum 留在文件里,DSH 读第二帧时报
70
+ * "corrupt Zstandard session log: invalid frame magic at byte N",连新建会话都失败。
71
+ * 因此:先按 FHD 判断补 4 字节,再以「下一帧帧头」为准做一次校正。
72
+ */
73
+ function firstFrameEnd(buf, expected) {
74
+ let lo = 1;
75
+ let hi = buf.length;
76
+ while (lo < hi) {
77
+ const mid = (lo + hi) >> 1;
78
+ let ok = false;
79
+ try {
80
+ ok = decodeFirstFrame(buf.subarray(0, mid)).equals(expected);
81
+ } catch {
82
+ ok = false;
83
+ }
84
+ if (ok) hi = mid;
85
+ else lo = mid + 1;
86
+ }
87
+ const min = lo;
88
+ const withChecksum = min + (frameHasChecksum(buf) ? 4 : 0);
89
+ // 帧尾就落在 min / min+4 / min+4 后面紧跟帧头,三种情况都认;否则退回 min+4
90
+ if (min >= buf.length || isFrameMagic(buf, min)) return min;
91
+ if (withChecksum >= buf.length || isFrameMagic(buf, withChecksum)) return withChecksum;
92
+ return Math.min(withChecksum, buf.length);
93
+ }
94
+
95
+ const projSpec = spec.projcache || {};
96
+ if (!fs.existsSync(sessionsRoot) && !Object.keys(projSpec).length) {
97
+ emit(result);
98
+ process.exit(0);
99
+ }
100
+
101
+ for (const [dirName, cwd] of Object.entries(dirs)) {
102
+ const dirPath = path.join(sessionsRoot, dirName);
103
+ if (!fs.existsSync(dirPath)) { result.missing++; continue; }
104
+ for (const entry of fs.readdirSync(dirPath, { withFileTypes: true })) {
105
+ if (!entry.isDirectory()) continue;
106
+ const file = path.join(dirPath, entry.name, 'session.v4.jsonl.zstd');
107
+ if (!fs.existsSync(file)) continue;
108
+ try {
109
+ const buf = fs.readFileSync(file);
110
+ const first = decodeFirstFrame(buf);
111
+ const nl = first.indexOf(0x0a);
112
+ if (nl < 0) throw new Error('第一帧里没有 header 行');
113
+ const header = JSON.parse(first.subarray(0, nl).toString('utf8'));
114
+ if (header.cwd === cwd) { result.alreadyOk++; continue; }
115
+
116
+ const text = first.toString('utf8');
117
+ // 只替换首帧里的 cwd 值,首帧其余文本(含可能的追加行)原样保留
118
+ const newText = text.replace(/"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/, `"cwd":${JSON.stringify(cwd)}`);
119
+ const newFrame = zlib.zstdCompressSync(Buffer.from(newText, 'utf8'));
120
+ let end = firstFrameEnd(buf, first);
121
+ // 历史写坏的文件里,第一帧边界之后还残留着 4 字节旧 checksum,
122
+ // 真正可用的下一帧在后面的帧头处——顺手把这段残缺尾巴丢掉(自愈)。
123
+ if (end < buf.length && !isFrameMagic(buf, end)) {
124
+ for (let k = end; k < Math.min(end + 9, buf.length); k++) {
125
+ if (isFrameMagic(buf, k)) { end = k; break; }
126
+ }
127
+ }
128
+ const rest = buf.subarray(end);
129
+ if (rest.length && !isFrameMagic(rest, 0)) {
130
+ throw new Error(`第一帧边界(${end})之后不是 zstd 帧头,跳过以免写坏后续帧`);
131
+ }
132
+ const rebuilt = Buffer.concat([newFrame, rest]);
133
+ if (rebuilt.length + 64 < buf.length) {
134
+ throw new Error(`重写后变小(${buf.length} → ${rebuilt.length}),正文可能被丢,已跳过`);
135
+ }
136
+ // 先自检、后落盘:任何一项不过都不写文件
137
+ const preText = decodeFirstFrame(rebuilt).toString('utf8');
138
+ const preHeader = JSON.parse(preText.slice(0, preText.indexOf('\n')));
139
+ if (preHeader.cwd !== cwd) throw new Error('自检失败:header.cwd 未生效,未写入');
140
+ // 自检看的是「新首帧之后」,所以用新帧长度,不是旧文件的 end
141
+ if (rebuilt.length > newFrame.length && !isFrameMagic(rebuilt, newFrame.length)) {
142
+ throw new Error(`自检失败:第 ${newFrame.length} 字节处不是下一帧帧头,未写入`);
143
+ }
144
+ fs.writeFileSync(file, rebuilt);
145
+
146
+ const verifyText = decodeFirstFrame(fs.readFileSync(file)).toString('utf8');
147
+ const verifyHeader = JSON.parse(verifyText.slice(0, verifyText.indexOf('\n')));
148
+ if (verifyHeader.cwd !== cwd) throw new Error('写回后校验失败:header.cwd 未生效');
149
+ result.fixed++;
150
+ } catch (e) {
151
+ result.failed.push({ file, error: e.message });
152
+ }
153
+ }
154
+ }
155
+
156
+ // projcache(<home>\storages\session_projcache\sessions\<sessionId>.json)里也存着
157
+ // record.identity.cwd。它是纯 JSON,可以安全地只替换那一个字符串,其余字节不动。
158
+ // 不换的话,B 机打开这些会话时 cwd 仍指 A 机的目录,历史对话回不到正确工作区。
159
+ const projMap = projSpec;
160
+ const projDir = path.join(home, 'storages', 'session_projcache', 'sessions');
161
+ result.projFixed = 0;
162
+ result.projAlreadyOk = 0;
163
+ result.projFailed = [];
164
+ if (Object.keys(projMap).length && fs.existsSync(projDir)) {
165
+ for (const entry of fs.readdirSync(projDir, { withFileTypes: true })) {
166
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.json')) continue;
167
+ const sid = entry.name.slice(0, -5);
168
+ const target = projMap[sid];
169
+ if (!target) continue;
170
+ const file = path.join(projDir, entry.name);
171
+ try {
172
+ const text = fs.readFileSync(file, 'utf8');
173
+ const doc = JSON.parse(text);
174
+ const cur = doc && doc.record && doc.record.identity && doc.record.identity.cwd;
175
+ if (typeof cur !== 'string') continue;
176
+ if (cur === target) { result.projAlreadyOk++; continue; }
177
+ // 只换第一处出现(record.identity.cwd 在文件靠前位置),其余字节原样保留
178
+ const re = /"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/;
179
+ const m = re.exec(text);
180
+ if (!m) throw new Error('找不到 identity.cwd 的字面位置');
181
+ const from = m[1];
182
+ const to = JSON.stringify(target);
183
+ if (from === to) { result.projAlreadyOk++; continue; }
184
+ const next = text.slice(0, m.index) + '"cwd": ' + to + text.slice(m.index + m[0].length);
185
+ // 只在「内容真的没变」时算已正确。早先这里用 next.length === text.length 判等,
186
+ // 两台机器路径长度相同时(D:\DeepSeekHarness → E:\DeepSeekHarness 这种)会把
187
+ // 该改的文件误判成「本就正确」,cwd 就留在源机路径上(隔离环境实测抓到)。
188
+ if (next === text) { result.projAlreadyOk++; continue; }
189
+ fs.writeFileSync(file, next, 'utf8');
190
+ const check = JSON.parse(fs.readFileSync(file, 'utf8'));
191
+ if (check.record.identity.cwd !== target) throw new Error('写回后校验失败');
192
+ result.projFixed++;
193
+ } catch (e) {
194
+ result.projFailed.push({ file, error: e.message });
195
+ }
196
+ }
197
+ }
198
+
199
+ emit(result);
200
+ process.exit((result.failed.length || result.projFailed.length) ? 1 : 0);
@@ -0,0 +1,259 @@
1
+ /**
2
+ * 客户端半身(client.js)的自检:
3
+ * node tools/clientcheck.mjs
4
+ *
5
+ * 浏览器模块表在 Node 里不存在,所以这里造一个最小的 window.__ModuleLoader__、react 替身,
6
+ * 以及 CommonJS 的 exports/module(client.js 与官方插件一样用 exports.name/inject/apply 导出)。
7
+ *
8
+ * 验证三件事(真实 UI 效果仍以重启后目视为准):
9
+ * 1. 模块能按约定加载并导出 name / inject / apply;
10
+ * 2. apply() 在 左侧栏 + main 面板 + 设置页 三处都成功注册,且 inject 回调返回回收函数;
11
+ * 3. 各组件在"无数据 / 有数据"两种状态下渲染不抛(侧栏图标能吃 size 参数)。
12
+ */
13
+ import { readFileSync } from 'node:fs'
14
+ import { dirname, join } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+
17
+ const here = dirname(fileURLToPath(import.meta.url))
18
+ const source = readFileSync(join(here, '..', 'client.js'), 'utf8')
19
+ // 期望的导出名直接取 package.json 的 name,改包名时这里跟着走,不用手工同步
20
+ const pkgName = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8')).name
21
+
22
+ let failures = 0
23
+ function check(label, cond, detail = '') {
24
+ if (cond) console.log(` [OK] ${label}`)
25
+ else { failures++; console.log(` [X] ${label}${detail ? ' — ' + detail : ''}`) }
26
+ }
27
+
28
+ // --- react 替身:createElement 只记录结构,hooks 给可用的假实现 ---
29
+ const reactShim = {
30
+ createElement: (type, props, ...children) => ({ type, props: props || {}, children }),
31
+ useState: (initial) => [initial, () => { }],
32
+ useEffect: () => { },
33
+ useCallback: (fn) => fn,
34
+ useMemo: (fn) => fn(),
35
+ useRef: (v) => ({ current: v }),
36
+ Fragment: 'Fragment',
37
+ }
38
+
39
+ const requireFn = (id) => {
40
+ if (id === 'react') return reactShim
41
+ throw new Error('未知模块:' + id)
42
+ }
43
+
44
+ /** 在造好的环境里跑 client.js,返回 factory 的产物(即 module.exports)。
45
+ * 故意不提供外层 exports/module:真实加载器也不提供,bundle 必须在 factory 内部自建,
46
+ * 否则真实环境里就是 "import failed"。 */
47
+ function loadClient(fetchImpl) {
48
+ let loaded
49
+ const windowStub = {
50
+ __ModuleLoader__: { load: (entry) => { loaded = entry.factory(requireFn) } },
51
+ }
52
+ const run = new Function('window', 'fetch', source)
53
+ run(windowStub, fetchImpl)
54
+ return loaded
55
+ }
56
+
57
+ console.log('== dsh-config-sync 客户端半身自检 ==')
58
+
59
+ // 无副作用的 fetch:组件在无数据状态下不该真的发请求(useEffect 在替身里是 noop)
60
+ const noopFetch = async () => ({ ok: true, status: 200, text: async () => '{}' })
61
+
62
+ let exportsObj
63
+ try {
64
+ exportsObj = loadClient(noopFetch)
65
+ check('模块加载', Boolean(exportsObj))
66
+ } catch (e) {
67
+ check('模块加载', false, String(e && e.message))
68
+ }
69
+
70
+ check('导出 name 正确', exportsObj && exportsObj.name === pkgName, String(exportsObj && exportsObj.name))
71
+ check('导出 inject 含 slots', Boolean(exportsObj && exportsObj.inject && exportsObj.inject.includes('slots')), JSON.stringify(exportsObj && exportsObj.inject))
72
+ check('导出 apply 是函数', typeof (exportsObj && exportsObj.apply) === 'function')
73
+
74
+ // --- 记录 apply() 的注册行为 ---
75
+ const regs = []
76
+ const recycle = []
77
+ const seq = [] // inject / register 的真实调用顺序,用来断言嵌套关系
78
+ const fakeCtx = {
79
+ slots: {
80
+ inject: (slot, cb) => {
81
+ seq.push('inject:' + slot)
82
+ const stop = cb()
83
+ recycle.push({ slot, stop })
84
+ return () => { }
85
+ },
86
+ register: (meta, comp) => {
87
+ seq.push('register:' + meta.name)
88
+ regs.push({ slot: meta.name, id: meta.id, key: meta.key, order: meta.order, label: meta.label, comp })
89
+ return () => { }
90
+ },
91
+ },
92
+ }
93
+
94
+ try {
95
+ exportsObj.apply(fakeCtx)
96
+ check('apply() 未抛异常', true)
97
+ } catch (e) {
98
+ check('apply() 未抛异常', false, String(e && e.message))
99
+ }
100
+
101
+ const sidebarRow = regs.find((r) => r.slot === 'sidebar.panellist')
102
+ const mainPanel = regs.find((r) => r.slot === 'main')
103
+ const settingsRow = regs.find((r) => r.slot === 'settings.general.item')
104
+
105
+ check('注册了左侧栏一行(sidebar.panellist)', Boolean(sidebarRow))
106
+ check('侧栏行 id 与 main 面板 key 一致', Boolean(sidebarRow && mainPanel && sidebarRow.id === mainPanel.key), `${sidebarRow && sidebarRow.id} / ${mainPanel && mainPanel.key}`)
107
+ check('侧栏行带 order 与 label', Boolean(sidebarRow && typeof sidebarRow.order === 'number' && typeof sidebarRow.label === 'function'), `${sidebarRow && sidebarRow.order} / ${typeof (sidebarRow && sidebarRow.label)}`)
108
+ check('注册了设置 → 通用 摘要行', Boolean(settingsRow))
109
+ check('客户端会调 /config-sync/settings 保存远端与私钥', /\/config-sync\/settings/.test(source))
110
+ check('客户端有可编辑的「本机仓库」卡(repoPath 走设置接口)', source.includes('function RepoCard') && source.includes('callSettings({ repoPath: path })'))
111
+ check('没配仓库时强制停在编辑态、且不提供取消', /forced/.test(source) && /forced \? null :/.test(source))
112
+ check('没配仓库时生成按钮被禁用', source.includes('disabled: busy || !canPush || noRemote'))
113
+ check('云端仓库缺配置时也强制编辑态(无取消)', /missing \? null :/.test(source) && source.includes('云端仓库地址'))
114
+ check('云端仓库没配时推送/拉取禁用、还原仍可用',
115
+ source.includes('disabled: busy || !canPull || noRemote')
116
+ && source.includes("disabled: busy || !hasRepoPath, onClick: () => prepare('restore')"))
117
+ check('面板有「提交说明」输入(生成推送脚本时带上)', source.includes('提交说明') && source.includes('prepare(\'push\', note)'))
118
+ check('按钮文案用中文(推送 / 拉取)', source.includes("'只生成推送'") && source.includes("'只生成拉取'"))
119
+ check('每个 inject 回调都返回了回收函数', recycle.length === 3 && recycle.every((r) => typeof r.stop === 'function'), `实际 ${recycle.length} 个`)
120
+
121
+ // 关键契约:sidebar.panellist 必须先被 inject,再往里 register(只 inject main 是无效的)
122
+ const idxInjectSidebar = seq.indexOf('inject:sidebar.panellist')
123
+ const idxInjectMain = seq.indexOf('inject:main')
124
+ const idxRegSidebar = seq.indexOf('register:sidebar.panellist')
125
+ const idxRegMain = seq.indexOf('register:main')
126
+ check('inject 顺序是 main → sidebar.panellist(嵌套)', idxInjectMain >= 0 && idxInjectSidebar > idxInjectMain, seq.join(' > '))
127
+ check('侧栏行在 inject:sidebar.panellist 之后才注册', idxRegSidebar > idxInjectSidebar && idxInjectSidebar >= 0, seq.join(' > '))
128
+ check('main 面板在 inject:main 之后注册', idxRegMain > idxInjectMain && idxInjectMain >= 0, seq.join(' > '))
129
+
130
+ function renderQuiet(label, factory) {
131
+ try {
132
+ const tree = factory()
133
+ const walk = (n) => {
134
+ if (!n || typeof n !== 'object') return
135
+ if (Array.isArray(n)) { n.forEach(walk); return }
136
+ if (n.children) n.children.forEach(walk)
137
+ }
138
+ walk(tree)
139
+ check(label, Boolean(tree))
140
+ return tree
141
+ } catch (e) {
142
+ check(label, false, String(e && e.message))
143
+ return null
144
+ }
145
+ }
146
+
147
+ renderQuiet('侧栏图标 size=14 可渲染', () => sidebarRow.comp({ size: 14 }))
148
+ renderQuiet('侧栏图标缺省 size 可渲染', () => sidebarRow.comp({}))
149
+ renderQuiet('主面板「无数据」可渲染', () => mainPanel.comp({}))
150
+ renderQuiet('设置摘要行「无数据」可渲染', () => settingsRow.comp({}))
151
+
152
+ // --- 有数据状态:fetch 返回一份体检 JSON(组件内部读取字段,渲染路径要能跑通) ---
153
+ const sample = {
154
+ ok: true,
155
+ at: 1762000000000,
156
+ repo: { path: 'D:\\dsh-config', exists: true, branch: 'main', head: '9acc303 feat: x', dirty: 0, ahead: 0, behind: 2 },
157
+ version: { local: '0.2.2-rc.1', contract: '0.2.2-rc.1', electron: '44.7.0', match: true },
158
+ bundles: { total: 25, unresolved: [] },
159
+ deps: { total: 21, missing: [] },
160
+ advice: ['仓库落后 2 个提交:退出 DSH 后执行 pull'],
161
+ auto: {
162
+ pull: false, push: false, restart: true, checking: false,
163
+ lastCheckAt: 0, lastCheckError: '', drift: null, pending: null, watcherStartedAt: 0,
164
+ script: 'C:\\Users\\x\\.dsh\\plugins\\dsh-config-sync\\runtime\\post-exit.ps1',
165
+ lastResult: {
166
+ mode: 'pull', ok: true, at: 1762100000000, code: 0,
167
+ message: '云端配置已拉取到本机', restored: false,
168
+ log: 'C:\\Users\\x\\.dsh\\logs\\auto-sync-pull-20261111-123456.log',
169
+ },
170
+ },
171
+ backup: {
172
+ root: 'C:\\Users\\x\\.dsh\\backups',
173
+ exists: true,
174
+ latest: 'C:\\Users\\x\\.dsh\\backups\\config-20261110-212944',
175
+ latestAt: 1762100000000,
176
+ count: 3,
177
+ latestFiles: 136,
178
+ candidates: [],
179
+ },
180
+ remote: {
181
+ url: 'git@gitee.com:qcwygm/dsh-config.git',
182
+ urlSource: 'git',
183
+ sshKey: 'C:\\Users\\x\\.ssh\\id_ed25519_gitee',
184
+ sshKeyExists: true,
185
+ sshKeyFrom: 'default',
186
+ sshConfig: true,
187
+ settingsPath: 'C:\\Users\\x\\.dsh\\dsh-config-sync.json',
188
+ },
189
+ paths: { appRoot: 'D:\\DeepSeekHarness', dshHome: 'C:\\Users\\x\\.dsh', profileDir: 'C:\\Users\\x\\.dsh\\profiles\\desktop' },
190
+ }
191
+
192
+ // 把 useSync 的数据注入路径替换掉不现实,这里改为直接验证 summarize 等纯函数所用字段的取值不抛:
193
+ // 用 useState 替身的另一种形态先把 data 注入组件(重新造一次环境,useState 第一次调用返回 sample)
194
+ function loadClientWithData(fetchImpl) {
195
+ let loaded
196
+ const windowStub = { __ModuleLoader__: { load: (entry) => { loaded = entry.factory(requireFn) } } }
197
+ const mod = { exports: {} }
198
+ // react 替身:useState 首次调用给 sample,第二次(made/open/busy)给默认值
199
+ let calls = 0
200
+ const reactWithData = Object.assign({}, reactShim, {
201
+ useState: (initial) => {
202
+ calls++
203
+ if (calls === 1) return [sample, () => { }]
204
+ return [initial, () => { }]
205
+ },
206
+ })
207
+ const run = new Function('window', 'fetch', 'exports', 'module', 'reactOverride', source)
208
+ run(windowStub, fetchImpl, mod.exports, mod, reactWithData)
209
+ return loaded
210
+ }
211
+
212
+ // 注意:上面的 reactOverride 无法注入(client.js 内部 require('react')),
213
+ // 因此"有数据"渲染改为直接喂一个 data 形状给面板所用的小组件,验证字段访问路径不抛。
214
+ const dataShape = sample
215
+ try {
216
+ const Kv = (props) => ({ type: 'kv', props })
217
+ void Kv
218
+ check('体检数据字段齐全(供组件读取)',
219
+ Boolean(dataShape.repo && dataShape.version && dataShape.bundles && dataShape.deps && Array.isArray(dataShape.advice)))
220
+ check('版本不一致时能算出(match 字段)', dataShape.version.match === true)
221
+ check('落后数量是数字', typeof dataShape.repo.behind === 'number')
222
+ check('体检数据带备份快照地址(页面要显示还原快照)',
223
+ Boolean(dataShape.backup && dataShape.backup.latest && typeof dataShape.backup.count === 'number'),
224
+ dataShape.backup && dataShape.backup.latest)
225
+ check('体检数据带远端地址与私钥(云端仓库卡用)',
226
+ Boolean(dataShape.remote && dataShape.remote.url && dataShape.remote.sshKey && dataShape.remote.settingsPath),
227
+ JSON.stringify(dataShape.remote && { url: dataShape.remote.url, key: dataShape.remote.sshKey }))
228
+ check('体检数据带自动同步开关与漂移状态(自动同步卡用)',
229
+ Boolean(dataShape.auto) && typeof dataShape.auto.pull === 'boolean' &&
230
+ typeof dataShape.auto.push === 'boolean' && typeof dataShape.auto.script === 'string',
231
+ JSON.stringify(dataShape.auto && { pull: dataShape.auto.pull, push: dataShape.auto.push }))
232
+ check('客户端会调 /config-sync/auto 控制自动同步', source.includes('/config-sync/auto'))
233
+ check('体检数据带上次自动同步结果(启动弹提示用)',
234
+ Boolean(dataShape.auto.lastResult) && typeof dataShape.auto.lastResult.ok === 'boolean' &&
235
+ typeof dataShape.auto.lastResult.at === 'number',
236
+ JSON.stringify(dataShape.auto.lastResult && { ok: dataShape.auto.lastResult.ok, at: dataShape.auto.lastResult.at }))
237
+ check('打开面板会自动检查云端(无手动点击也会跑 check)', /callAuto\(\{ action: 'check'/.test(source))
238
+ check('云端状态在标题行右侧(自动检查,靠徽标红绿显示,无手动按钮)',
239
+ source.includes('云端检查中') && source.includes('云端与本机不一致') && !source.includes('立即检查'))
240
+ check('本机路径区默认不进页面(只有标题行按钮点开才渲染)',
241
+ source.includes('const rootsCard = showRoots ? h(RootsCard, { onRootsSaved: refresh }) : null') &&
242
+ !source.includes('props.forceShow'),
243
+ '缺 showRoots 三元 / 仍留着 forceShow')
244
+ check('标题行按钮把告警数量挂在文案上(三类合计)',
245
+ source.includes('项告警') && source.includes('data.localPaths && data.localPaths.alert'))
246
+ check('status 请求带超时与自动重试(一次抖动不该让面板卡在「读取失败」)',
247
+ source.includes('new AbortController()') && source.includes('15000')
248
+ && source.includes('已自动重试 3 次'),
249
+ '缺 AbortController 超时 / 缺重试文案')
250
+ check('备份列表不再逐个显示体积(体积由资源管理器看,status 不为此递归统计)',
251
+ !source.includes('个文件 · ${size(s.bytes)}'),
252
+ '仍在列表里渲染体积')
253
+ } catch (e) {
254
+ check('体检数据字段齐全', false, String(e && e.message))
255
+ }
256
+
257
+ console.log('')
258
+ console.log(failures === 0 ? '结论:全部通过(真实 UI 仍需重启后目视确认)' : `结论:${failures} 项失败`)
259
+ process.exit(failures === 0 ? 0 : 1)
@@ -0,0 +1,79 @@
1
+ <#
2
+ 打包 dsh-config-sync-plugin 插件 tgz(发布用,自包含:只读本仓库)
3
+
4
+ 用法
5
+ pwsh -File tools\pack-plugin.ps1 # 打 releases\dsh-config-sync-plugin-<version>.tgz,并把 sha256 回填 version.json
6
+ pwsh -File tools\pack-plugin.ps1 -NoManifest # 只打包,不动 version.json
7
+ pwsh -File tools\pack-plugin.ps1 -Output x.tgz # 打到别处(不回填清单)
8
+
9
+ 要点
10
+ - 包内布局与 npm pack 一致:`package/` 前缀,内容按 package.json 的 files 字段收集,
11
+ 所以两种打包方式产出的条目相同(字节不同,谁打的就以谁的 sha256 为准)。
12
+ - 用 %SystemRoot%\System32\tar.exe(Windows 自带),不依赖 npm / 7z / pnpm。
13
+ - sha256 只在「输出落在 releases\、文件名与 version.json 里的 tgz 对得上」时才回填,
14
+ 避免把临时包的 hash 写进发布清单。
15
+ - 发布顺序:改代码 → 本脚本打包 → 更新 market-index.json 的 version 与 commit → 推送。
16
+ #>
17
+ param(
18
+ [string]$RepoRoot = (Split-Path -Parent $PSScriptRoot),
19
+ [string]$Output,
20
+ [switch]$NoManifest
21
+ )
22
+ $ErrorActionPreference = 'Stop'
23
+
24
+ $pkgFile = Join-Path $RepoRoot 'package.json'
25
+ if (-not (Test-Path -LiteralPath $pkgFile)) { throw "不是插件仓库根(缺 package.json):$RepoRoot" }
26
+ $pkg = Get-Content -LiteralPath $pkgFile -Raw -Encoding utf8 | ConvertFrom-Json
27
+ $version = [string]$pkg.version
28
+ if (-not $Output) { $Output = Join-Path $RepoRoot ("releases\dsh-config-sync-plugin-{0}.tgz" -f $version) }
29
+ $outFull = [IO.Path]::GetFullPath($Output)
30
+ $outName = Split-Path -Leaf $outFull
31
+
32
+ $stage = Join-Path ([IO.Path]::GetTempPath()) ("pack-dsh-config-sync-" + [Guid]::NewGuid().ToString('N').Substring(0, 8))
33
+ $pkgDir = Join-Path $stage 'package'
34
+ New-Item -ItemType Directory -Path $pkgDir -Force | Out-Null
35
+ try {
36
+ # files 字段是唯一口径:漏了 runtime\ 会静默打出体积偏小、装上也跑不起来的坏包
37
+ $files = @($pkg.files)
38
+ if ($files.Count -eq 0) { $files = @('index.js', 'client.js', 'package.json', 'cordis.patch.yml', 'README.md', 'README.en.md', 'LICENSE', 'runtime', 'tools') }
39
+ foreach ($item in $files) {
40
+ $from = Join-Path $RepoRoot $item
41
+ if (Test-Path -LiteralPath $from) { Copy-Item -LiteralPath $from -Destination (Join-Path $pkgDir $item) -Recurse }
42
+ }
43
+ # package.json 必须带进包(npm 装包靠它认入口)
44
+ Copy-Item -LiteralPath $pkgFile -Destination (Join-Path $pkgDir 'package.json') -Force
45
+
46
+ $parent = Split-Path -Parent $outFull
47
+ if (-not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
48
+ if (Test-Path -LiteralPath $outFull) { Remove-Item -LiteralPath $outFull -Force }
49
+ $tar = Join-Path $env:SystemRoot 'System32\tar.exe'
50
+ & $tar -czf $outFull -C $stage package
51
+ if ($LASTEXITCODE -ne 0) { throw "tar 打包失败,退出码 $LASTEXITCODE" }
52
+
53
+ $size = (Get-Item -LiteralPath $outFull).Length
54
+ $sha = (Get-FileHash -LiteralPath $outFull -Algorithm SHA256).Hash.ToLower()
55
+ $count = (& $tar -tzf $outFull | Measure-Object).Count
56
+ "已打包:$outFull($size 字节,$count 个条目,版本 $version)"
57
+ "sha256:$sha"
58
+
59
+ if (-not $NoManifest) {
60
+ $manFile = Join-Path $RepoRoot 'version.json'
61
+ if (Test-Path -LiteralPath $manFile) {
62
+ $man = Get-Content -LiteralPath $manFile -Raw -Encoding utf8 | ConvertFrom-Json
63
+ $wantTgz = [string]$man.tgz
64
+ $wantName = Split-Path -Leaf ($wantTgz -replace '/', '\')
65
+ if ($wantName -and $wantName -eq $outName) {
66
+ $raw = Get-Content -LiteralPath $manFile -Raw -Encoding utf8
67
+ if ($raw -match '"sha256"\s*:\s*"[^"]*"') {
68
+ $new = [regex]::Replace($raw, '"sha256"\s*:\s*"[^"]*"', ('"sha256":"' + $sha + '"'), 1)
69
+ [IO.File]::WriteAllText($manFile, $new, (New-Object Text.UTF8Encoding($false)))
70
+ "已回填 version.json 的 sha256($outName)"
71
+ } else { "version.json 里没有 sha256 字段,未回填" }
72
+ } else {
73
+ "version.json 里的 tgz 是「$wantTgz」,与本次输出「$outName」不一致,未回填"
74
+ }
75
+ }
76
+ }
77
+ } finally {
78
+ Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
79
+ }