dsh-gallery 0.14.1 → 0.14.4

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.
@@ -1,187 +1,277 @@
1
- /**
2
- * 会话索引 —— 把「所有会话产出了哪些文件」建成一张表。
3
- *
4
- * 用途:让「全局资产」能按对话分组展示,而不是一堆乱七八糟的文件。
5
- *
6
- * 为什么需要缓存:
7
- * 全量扫描 108 个会话日志(80 MB)实测耗时 1639 ms,
8
- * 而画廊每 5 秒刷新一次 → 不可能每次都全量解压。
9
- * 用「目录 mtime + 会话数」做键,没事就不重扫。
10
- *
11
- * 为什么用目录 mtime 而不是逐个文件:
12
- * 108 个文件各 stat 一次也有开销;会话目录增多或日志追加时,
13
- * 目录 mtime 会变,足够触发重扫。
14
- */
15
-
16
- import { promises as fsp } from 'node:fs'
17
- import path from 'node:path'
18
-
19
- /** 会话索引缓存:键是 sessionsDir,值是 { key, index }。 */
20
- const sessionIndexCache = new Map()
21
-
22
- /**
23
- * 扫出一个会话目录里的全部会话(含子会话)。
24
- * @param sessionsDir - 会话根目录。
25
- * @returns 会话目录信息数组。
26
- */
27
- async function listSessionDirs(sessionsDir) {
28
- const dirs = []
29
- let groups
30
- try {
31
- groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
32
- } catch {
33
- return dirs
34
- }
35
- for (const group of groups) {
36
- if (!group.isDirectory()) continue
37
- const gdir = path.join(sessionsDir, String(group.name))
38
- let sessions
39
- try {
40
- sessions = await fsp.readdir(gdir, { withFileTypes: true })
41
- } catch {
42
- continue
43
- }
44
- for (const s of sessions) {
45
- if (!s.isDirectory()) continue
46
- const sdir = path.join(gdir, String(s.name))
47
- const logPath = path.join(sdir, 'session.v4.jsonl.zstd')
48
- try {
49
- const st = await fsp.stat(logPath)
50
- if (!st.isFile()) continue
51
- dirs.push({
52
- sessionId: String(s.name),
53
- group: String(group.name),
54
- sessionDir: sdir,
55
- logPath,
56
- logMtime: st.mtimeMs,
57
- logSize: st.size,
58
- })
59
- } catch {
60
- // 没有日志就跳过
61
- }
62
- }
63
- }
64
- return dirs
65
- }
66
-
67
- /**
68
- * 从会话日志里提取标题。DSH 会写 `session/title` 事件。
69
- * @param logText - 解压后的日志文本。
70
- * @returns 标题字符串;没有则空串。
71
- */
72
- function extractSessionTitle(logText) {
73
- if (typeof logText !== 'string' || logText === '') return ''
74
- // 取最后一个 title(用户可能改过标题)
75
- let title = ''
76
- for (const line of logText.split('\n')) {
77
- if (!line.includes('session/title')) continue
78
- let o
79
- try { o = JSON.parse(line) } catch { continue }
80
- if (o?.type !== 'session/title') continue
81
- const t = o?.data?.title
82
- if (typeof t === 'string' && t.trim() !== '') title = t.trim()
83
- }
84
- return title
85
- }
86
-
87
- /**
88
- * 从会话日志首行读元信息(创建时间、cwd、父会话)。
89
- * @param logText - 解压后的日志文本。
90
- * @returns { createdAt, cwd, parentSession }
91
- */
92
- function extractSessionMeta(logText) {
93
- const fallback = { createdAt: 0, cwd: '', parentSession: '' }
94
- if (typeof logText !== 'string' || logText === '') return fallback
95
- const firstLine = logText.split('\n')[0]
96
- let o
97
- try { o = JSON.parse(firstLine) } catch { return fallback }
98
- return {
99
- createdAt: typeof o?.createdAt === 'number' ? o.createdAt : 0,
100
- cwd: typeof o?.cwd === 'string' ? o.cwd : '',
101
- parentSession: typeof o?.parentSession === 'string' ? o.parentSession : '',
102
- }
103
- }
104
-
105
- /**
106
- * 建立(或复用)会话索引。
107
- *
108
- * @param sessionsDir - 会话根目录。
109
- * @param opts - resolveOptions 的结果(要用到 roots / readSessionLogText / extractAssetInfo)。
110
- * @param deps - 依赖注入 { readSessionLogText, extractAssetInfo }。
111
- * @returns Map<sessionId, { sessionId, title, createdAt, cwd, parentSession, files: Map<abs, category>, maxMtime }>
112
- */
113
- export async function buildSessionIndex(sessionsDir, opts, deps) {
114
- const { readSessionLogText, extractAssetInfo } = deps
115
-
116
- // 缓存键:会话目录的 mtime + 当前会话数
117
- let dirKey
118
- try {
119
- const allDirs = await listSessionDirs(sessionsDir)
120
- dirKey = `${allDirs.length}|${allDirs.reduce((a, d) => Math.max(a, d.logMtime), 0)}`
121
- const cached = sessionIndexCache.get(sessionsDir)
122
- if (cached !== undefined && cached.key === dirKey) return cached.index
123
-
124
- const index = new Map()
125
-
126
- for (const d of allDirs) {
127
- const logText = await readSessionLogText(d.logPath)
128
- if (logText === '') continue
129
-
130
- const meta = extractSessionMeta(logText)
131
- const title = extractSessionTitle(logText)
132
- // 传会话开始时间:用于区分「用户素材」和「会话期间产出」的分类
133
- const assets = extractAssetInfo(logText, meta.createdAt)
134
-
135
- // 只看落在扫描目录内的路径
136
- const files = new Map()
137
- let maxMtime = meta.createdAt
138
- for (const [abs, info] of assets) {
139
- let ownerRoot = null
140
- for (const r of opts.roots) {
141
- if (isInsidePath(r, abs)) { ownerRoot = r; break }
142
- }
143
- if (ownerRoot === null) continue
144
- files.set(abs, info.category)
145
- try {
146
- const st = await fsp.stat(abs)
147
- if (st.mtimeMs > maxMtime) maxMtime = st.mtimeMs
148
- } catch {
149
- // 文件已删除就跳过
150
- }
151
- }
152
-
153
- if (files.size === 0) continue
154
-
155
- index.set(d.sessionId, {
156
- sessionId: d.sessionId,
157
- title,
158
- createdAt: meta.createdAt,
159
- cwd: meta.cwd,
160
- parentSession: meta.parentSession,
161
- files,
162
- maxMtime,
163
- logMtime: d.logMtime,
164
- })
165
- }
166
-
167
- sessionIndexCache.set(sessionsDir, { key: dirKey, index })
168
- return index
169
- } catch {
170
- return new Map()
171
- }
172
- }
173
-
174
- /** 路径是否在 root 内(避免循环依赖,这里内联一份最小实现)。 */
175
- function isInsidePath(root, abs) {
176
- const r = path.resolve(root)
177
- const a = path.resolve(abs)
178
- if (a === r) return true
179
- return a.startsWith(r + path.sep)
180
- }
181
-
182
- /**
183
- * 清空会话索引缓存(配置变化时调用)。
184
- */
185
- export function clearSessionIndexCache() {
186
- sessionIndexCache.clear()
187
- }
1
+ /**
2
+ * 会话索引 —— 把「所有会话产出了哪些文件」建成一张表。
3
+ *
4
+ * 用途:让「全局资产」能按对话分组展示,而不是一堆乱七八糟的文件。
5
+ *
6
+ * 为什么需要缓存:
7
+ * 全量扫描 108 个会话日志(80 MB)实测耗时 1639 ms,
8
+ * 而画廊每 5 秒刷新一次 → 不可能每次都全量解压。
9
+ * 用「目录 mtime + 会话数」做键,没事就不重扫。
10
+ *
11
+ * 为什么用目录 mtime 而不是逐个文件:
12
+ * 108 个文件各 stat 一次也有开销;会话目录增多或日志追加时,
13
+ * 目录 mtime 会变,足够触发重扫。
14
+ */
15
+
16
+ import { promises as fsp } from 'node:fs'
17
+ import path from 'node:path'
18
+
19
+ /**
20
+ * 单个会话日志的解析缓存:logPath → { key, entry }。
21
+ *
22
+ * 旧版用「所有日志里最新的 mtime」当整表缓存键,只要当前对话还在写日志,
23
+ * 这个键每次都变 → 每 5 秒自动刷新都把 100 MB 日志全量解压一遍(实测 3.6 秒)。
24
+ * 改成按日志逐条缓存后,活跃会话只重解它自己那一个日志(约几十毫秒)。
25
+ */
26
+ const sessionEntryCache = new Map()
27
+ /** 当前缓存对应的扫描目录指纹;用户改了根目录就整体失效。 */
28
+ let indexRootsKey = ''
29
+
30
+ /**
31
+ * 扫出一个会话目录里的全部会话(含子会话)。
32
+ * @param sessionsDir - 会话根目录。
33
+ * @returns 会话目录信息数组。
34
+ */
35
+ async function listSessionDirs(sessionsDir) {
36
+ const dirs = []
37
+ let groups
38
+ try {
39
+ groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
40
+ } catch {
41
+ return dirs
42
+ }
43
+ for (const group of groups) {
44
+ if (!group.isDirectory()) continue
45
+ const gdir = path.join(sessionsDir, String(group.name))
46
+ let sessions
47
+ try {
48
+ sessions = await fsp.readdir(gdir, { withFileTypes: true })
49
+ } catch {
50
+ continue
51
+ }
52
+ for (const s of sessions) {
53
+ if (!s.isDirectory()) continue
54
+ const sdir = path.join(gdir, String(s.name))
55
+ const logPath = path.join(sdir, 'session.v4.jsonl.zstd')
56
+ try {
57
+ const st = await fsp.stat(logPath)
58
+ if (!st.isFile()) continue
59
+ dirs.push({
60
+ sessionId: String(s.name),
61
+ group: String(group.name),
62
+ sessionDir: sdir,
63
+ logPath,
64
+ logMtime: st.mtimeMs,
65
+ logSize: st.size,
66
+ })
67
+ } catch {
68
+ // 没有日志就跳过
69
+ }
70
+ }
71
+ }
72
+ return dirs
73
+ }
74
+
75
+ /**
76
+ * 从会话日志里提取标题。DSH 会写 `session/title` 事件。
77
+ * @param logText - 解压后的日志文本。
78
+ * @returns 标题字符串;没有则空串。
79
+ */
80
+ function extractSessionTitle(logText) {
81
+ if (typeof logText !== 'string' || logText === '') return ''
82
+ // 取最后一个 title(用户可能改过标题)
83
+ let title = ''
84
+ for (const line of logText.split('\n')) {
85
+ if (!line.includes('session/title')) continue
86
+ let o
87
+ try { o = JSON.parse(line) } catch { continue }
88
+ if (o?.type !== 'session/title') continue
89
+ const t = o?.data?.title
90
+ if (typeof t === 'string' && t.trim() !== '') title = t.trim()
91
+ }
92
+ return title
93
+ }
94
+
95
+ /**
96
+ * 从会话日志首行读元信息(创建时间、cwd、父会话)。
97
+ * @param logText - 解压后的日志文本。
98
+ * @returns { createdAt, cwd, parentSession }
99
+ */
100
+ function extractSessionMeta(logText) {
101
+ const fallback = { createdAt: 0, cwd: '', parentSession: '' }
102
+ if (typeof logText !== 'string' || logText === '') return fallback
103
+ const firstLine = logText.split('\n')[0]
104
+ let o
105
+ try { o = JSON.parse(firstLine) } catch { return fallback }
106
+ return {
107
+ createdAt: typeof o?.createdAt === 'number' ? o.createdAt : 0,
108
+ cwd: typeof o?.cwd === 'string' ? o.cwd : '',
109
+ parentSession: typeof o?.parentSession === 'string' ? o.parentSession : '',
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 建立(或复用)会话索引。
115
+ *
116
+ * @param sessionsDir - 会话根目录。
117
+ * @param opts - resolveOptions 的结果(要用到 roots / readSessionLogText / extractAssetInfo)。
118
+ * @param deps - 依赖注入 { readSessionLogText, extractAssetInfo }。
119
+ * @returns Map<sessionId, { sessionId, title, createdAt, cwd, parentSession, files: Map<abs, category>, maxMtime }>
120
+ */
121
+ export async function buildSessionIndex(sessionsDir, opts, deps) {
122
+ const { readSessionLogText, extractAssetInfo } = deps
123
+ try {
124
+ // 列目录 + stat 115 个日志文件很便宜(约 10 ms),每次都做;
125
+ // 贵的「解压 + 逐行解析」只发生在 mtime/size 变了的那些日志上。
126
+ const allDirs = await listSessionDirs(sessionsDir)
127
+ // 扫描目录变了(面板里改 root)→ 旧缓存里的文件归属是按旧目录算的,必须全部重算
128
+ const rootsKey = (opts.roots ?? []).map((r) => path.resolve(r).toLowerCase()).join('|')
129
+ if (rootsKey !== indexRootsKey) {
130
+ sessionEntryCache.clear()
131
+ indexRootsKey = rootsKey
132
+ }
133
+ const index = new Map()
134
+ const livePaths = new Set()
135
+
136
+ for (const d of allDirs) {
137
+ livePaths.add(d.logPath)
138
+ const key = `${d.logMtime}|${d.logSize}`
139
+ const cached = sessionEntryCache.get(d.logPath)
140
+ if (cached !== undefined && cached.key === key) {
141
+ if (cached.entry !== null) index.set(d.sessionId, cached.entry)
142
+ continue
143
+ }
144
+
145
+ const logText = await readSessionLogText(d.logPath)
146
+ if (logText === '') {
147
+ sessionEntryCache.set(d.logPath, { key, entry: null })
148
+ continue
149
+ }
150
+
151
+ const meta = extractSessionMeta(logText)
152
+ const title = extractSessionTitle(logText)
153
+ // 传会话开始时间:用于区分「用户素材」和「会话期间产出」的分类
154
+ const assets = extractAssetInfo(logText, meta.createdAt)
155
+
156
+ // 只看落在扫描目录内的路径
157
+ const files = new Map()
158
+ let maxMtime = meta.createdAt
159
+ for (const [abs, info] of assets) {
160
+ let ownerRoot = null
161
+ for (const r of opts.roots) {
162
+ if (isInsidePath(r, abs)) { ownerRoot = r; break }
163
+ }
164
+ if (ownerRoot === null) continue
165
+ files.set(abs, info.category)
166
+ try {
167
+ const st = await fsp.stat(abs)
168
+ if (st.mtimeMs > maxMtime) maxMtime = st.mtimeMs
169
+ } catch {
170
+ // 文件已删除就跳过
171
+ }
172
+ }
173
+
174
+ if (files.size === 0) {
175
+ sessionEntryCache.set(d.logPath, { key, entry: null })
176
+ continue
177
+ }
178
+
179
+ const entry = {
180
+ sessionId: d.sessionId,
181
+ title,
182
+ createdAt: meta.createdAt,
183
+ cwd: meta.cwd,
184
+ parentSession: meta.parentSession,
185
+ files,
186
+ maxMtime,
187
+ logMtime: d.logMtime,
188
+ }
189
+ index.set(d.sessionId, entry)
190
+ sessionEntryCache.set(d.logPath, { key, entry })
191
+ }
192
+
193
+ // 日志目录被删掉时把对应缓存也清掉,避免常驻进程里无限堆积
194
+ for (const p of sessionEntryCache.keys()) {
195
+ if (!livePaths.has(p)) sessionEntryCache.delete(p)
196
+ }
197
+ return index
198
+ } catch {
199
+ return new Map()
200
+ }
201
+ }
202
+
203
+ /** 路径是否在 root 内(避免循环依赖,这里内联一份最小实现)。 */
204
+ function isInsidePath(root, abs) {
205
+ const r = path.resolve(root)
206
+ const a = path.resolve(abs)
207
+ if (a === r) return true
208
+ return a.startsWith(r + path.sep)
209
+ }
210
+
211
+ /**
212
+ * 清空会话索引缓存(配置变化时调用)。
213
+ */
214
+ export function clearSessionIndexCache() {
215
+ sessionEntryCache.clear()
216
+ indexRootsKey = ''
217
+ }
218
+
219
+ /**
220
+ * 会话状态注册表 —— 宿主官方字段,不是私有会话日志。
221
+ *
222
+ * 文件:<DSH_HOME>/storages/workspace.json
223
+ * · global.archivedSessionIds —— 宿主「归档会话」写这里(宿主 zod schema 实证)
224
+ * · tables.workspaces[*].sessionIds —— 每个工作区挂载的少量会话,**不是全量会话表**;
225
+ * 本机实测仅 15 个,而会话日志有 115 个,因此它只能读、绝不能用来推断「已删除」。
226
+ *
227
+ * 为什么需要它:画廊是按会话日志分组的,日志目录不会因为归档而消失,
228
+ * 于是「资产还在、对话已归档」的分组需要一个明确标注。
229
+ * 这里只做只读判定:不写宿主任何文件,也不改变分组原有的时间排序。
230
+ */
231
+ const sessionStateCache = new Map()
232
+
233
+ /** @returns {{ok:boolean, archived:Set<string>, known:Set<string>}} */
234
+ export async function readSessionStates(dshHome) {
235
+ const file = path.join(dshHome, 'storages', 'workspace.json')
236
+ try {
237
+ const st = await fsp.stat(file)
238
+ const key = `${st.mtimeMs}|${st.size}`
239
+ const cached = sessionStateCache.get(file)
240
+ if (cached !== undefined && cached.key === key) return cached.states
241
+ const raw = JSON.parse(await fsp.readFile(file, 'utf8'))
242
+ const archived = new Set(
243
+ Array.isArray(raw?.global?.archivedSessionIds) ? raw.global.archivedSessionIds : [],
244
+ )
245
+ const known = new Set()
246
+ for (const w of Object.values(raw?.tables?.workspaces ?? {})) {
247
+ if (Array.isArray(w?.sessionIds)) for (const id of w.sessionIds) known.add(id)
248
+ }
249
+ const states = { ok: true, archived, known }
250
+ sessionStateCache.set(file, { key, states })
251
+ return states
252
+ } catch {
253
+ // 读不到就全部当 active:标注功能降级,但绝不影响扫描
254
+ return { ok: false, archived: new Set(), known: new Set() }
255
+ }
256
+ }
257
+
258
+ /**
259
+ * 单个会话的状态。
260
+ * active —— 默认;没有反证就当可打开,绝不预先禁用「打开对话」
261
+ * archived —— 命中宿主官方 global.archivedSessionIds(唯一可信的归档证据)
262
+ * unassigned —— 历史资产,本来就查不到归属会话,不加标注
263
+ *
264
+ * ⚠️ 2026-11-10 修复(老板报的 bug):
265
+ * 旧版把「不在 tables.workspaces[*].sessionIds 里」直接判成 deleted,
266
+ * 但本机实测该注册表只有 15 个会话,而会话日志有 115 个 —— 左侧列表里
267
+ * 正常开着的会话几乎全被误标成「会话已删除」,连「打开对话」都被禁用。
268
+ * 宿主没有 deletedSessionIds 这类官方字段,删除状态无法离线可靠推断,
269
+ * 因此这里只保留官方归档字段;真正打不开的交给客户端点击时实测标注。
270
+ *
271
+ * 只用于「标注」,绝不参与分组排序。
272
+ */
273
+ export function stateOfSession(sessionId, states) {
274
+ if (sessionId === null || sessionId === undefined || sessionId === '') return 'unassigned'
275
+ if (states?.archived?.has(sessionId)) return 'archived'
276
+ return 'active'
277
+ }
package/install.mjs ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-gallery · 本地目录安装脚本(幂等、非交互、跨平台)
4
+ *
5
+ * node install.mjs # 自动选 profile 并安装
6
+ * node install.mjs --profile desktop # 指定 profile
7
+ * node install.mjs --dry-run # 只打印将要做什么,不写任何文件
8
+ *
9
+ * 行为:定位 DSH_HOME(默认 ~/.dsh)→ 选 profile → 校验源文件 →
10
+ * 复制插件文件 → 在 <profile>/package.json 的 dsh.profile.bundles 注册 →
11
+ * 首次注册前备份 package.json。装完必须完全重启 DSH。
12
+ */
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+ import os from 'node:os'
16
+ import { fileURLToPath } from 'node:url'
17
+
18
+ const SOURCE = path.dirname(fileURLToPath(import.meta.url))
19
+ const argv = process.argv.slice(2)
20
+ const dryRun = argv.includes('--dry-run')
21
+ const flagValue = (name) => {
22
+ const i = argv.indexOf(name)
23
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null
24
+ }
25
+ const wantedProfile = flagValue('--profile')
26
+
27
+ const fail = (message) => {
28
+ console.error('[dsh-gallery 安装失败] ' + message)
29
+ process.exit(1)
30
+ }
31
+ const log = (message) => console.log((dryRun ? '[预演] ' : '') + message)
32
+
33
+ const home = process.env.DSH_HOME
34
+ ? path.resolve(process.env.DSH_HOME)
35
+ : path.join(os.homedir(), '.dsh')
36
+ const profilesDir = path.join(home, 'profiles')
37
+
38
+ if (!fs.existsSync(profilesDir)) fail('找不到 profiles 目录:' + profilesDir)
39
+ const profiles = fs.readdirSync(profilesDir, { withFileTypes: true })
40
+ .filter((entry) => entry.isDirectory())
41
+ .map((entry) => entry.name)
42
+ if (profiles.length === 0) fail('profiles 目录是空的:' + profilesDir)
43
+
44
+ const profile = wantedProfile
45
+ ?? (profiles.length === 1 ? profiles[0] : (profiles.includes('desktop') ? 'desktop' : profiles[0]))
46
+ if (!profiles.includes(profile)) {
47
+ fail('profile「' + profile + '」不存在。可用:' + profiles.join('、'))
48
+ }
49
+
50
+ const profileDir = path.join(profilesDir, profile)
51
+ const profilePkgPath = path.join(profileDir, 'package.json')
52
+ const targetDir = path.join(profileDir, 'node_modules', 'dsh-gallery')
53
+ if (!fs.existsSync(profilePkgPath)) fail('profile 缺少 package.json:' + profilePkgPath)
54
+
55
+ // 源侧必需文件
56
+ const requiredFiles = [
57
+ 'index.js', 'client.js', 'session-index.js', 'package.json',
58
+ 'cordis.patch.yml', 'icon.svg', 'README.md', 'LICENSE', 'CHANGELOG.md',
59
+ ]
60
+ for (const file of requiredFiles) {
61
+ if (!fs.existsSync(path.join(SOURCE, file))) fail('源文件缺失:' + file)
62
+ }
63
+ for (const dir of ['host', 'locale']) {
64
+ if (!fs.existsSync(path.join(SOURCE, dir))) fail('源目录缺失:' + dir + '/')
65
+ }
66
+
67
+ // 复制清单:根文件 + 整个 host/ + locale/ + 可选 docs/screenshots/
68
+ const entries = [
69
+ ...requiredFiles.map((file) => ({ from: path.join(SOURCE, file), to: path.join(targetDir, file), kind: 'file' })),
70
+ { from: path.join(SOURCE, 'host'), to: path.join(targetDir, 'host'), kind: 'dir' },
71
+ { from: path.join(SOURCE, 'locale'), to: path.join(targetDir, 'locale'), kind: 'dir' },
72
+ ]
73
+ const shots = path.join(SOURCE, 'docs', 'screenshots')
74
+ if (fs.existsSync(shots)) {
75
+ entries.push({ from: shots, to: path.join(targetDir, 'docs', 'screenshots'), kind: 'dir' })
76
+ }
77
+
78
+ // 注册位置:dsh.profile.bundles(不是顶层 bundles)
79
+ const profilePkg = JSON.parse(fs.readFileSync(profilePkgPath, 'utf8'))
80
+ const bundles = profilePkg.dsh?.profile?.bundles
81
+ const alreadyRegistered = Array.isArray(bundles) && bundles.includes('dsh-gallery')
82
+ const backupPath = path.join(profileDir, 'package.json.bak-dsh-gallery')
83
+ const dep = profilePkg.dependencies?.['dsh-gallery']
84
+
85
+ log('DSH 主目录:' + home)
86
+ log('profile:' + profile + '(' + profileDir + ')')
87
+ log('安装目标:' + targetDir)
88
+ log('复制:' + entries.length + ' 项(' + requiredFiles.join('、') + '、host/、locale/' + (fs.existsSync(shots) ? '、docs/screenshots/' : '') + ')')
89
+ log('注册:' + (alreadyRegistered ? '已注册,跳过' : '写入 dsh.profile.bundles'))
90
+ log('备份:' + (fs.existsSync(backupPath) ? '已存在,保留不覆盖' : '首次注册前备份 → ' + backupPath))
91
+
92
+ if (dep && String(dep).startsWith('file:')) {
93
+ console.warn('[提醒] profile 依赖里 dsh-gallery 是 file: 本地路径(' + dep + ')。')
94
+ console.warn(' 如果它指向的不是本脚本所在目录,重启 DSH 时包管理器可能把这里的文件覆盖掉。')
95
+ console.warn(' 建议改成 npm 版本,或确认 file: 路径一致。')
96
+ }
97
+
98
+ if (dryRun) {
99
+ console.log('[预演结束] 未写入任何文件。')
100
+ process.exit(0)
101
+ }
102
+
103
+ function copyEntry(entry) {
104
+ if (entry.kind === 'file') {
105
+ fs.mkdirSync(path.dirname(entry.to), { recursive: true })
106
+ fs.copyFileSync(entry.from, entry.to)
107
+ return 1
108
+ }
109
+ let count = 0
110
+ fs.mkdirSync(entry.to, { recursive: true })
111
+ for (const item of fs.readdirSync(entry.from, { withFileTypes: true })) {
112
+ const from = path.join(entry.from, item.name)
113
+ const to = path.join(entry.to, item.name)
114
+ count += copyEntry({ from, to, kind: item.isDirectory() ? 'dir' : 'file' })
115
+ }
116
+ return count
117
+ }
118
+
119
+ // 先备份,再复制,最后注册 —— 任一步失败,原 package.json 都留有回退点
120
+ if (!fs.existsSync(backupPath)) fs.copyFileSync(profilePkgPath, backupPath)
121
+
122
+ let copied = 0
123
+ for (const entry of entries) copied += copyEntry(entry)
124
+ log('已复制 ' + copied + ' 个文件')
125
+
126
+ if (!alreadyRegistered) {
127
+ profilePkg.dsh ??= {}
128
+ profilePkg.dsh.profile ??= {}
129
+ profilePkg.dsh.profile.bundles ??= []
130
+ profilePkg.dsh.profile.bundles.push('dsh-gallery')
131
+ fs.writeFileSync(profilePkgPath, JSON.stringify(profilePkg, null, 2) + '\n', 'utf8')
132
+ log('已写入 dsh.profile.bundles')
133
+ }
134
+
135
+ console.log('[dsh-gallery] 安装完成。请完全退出 DSH 再打开(刷新页面不够)。')