dsh-context-kit 0.1.0 → 0.1.1

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,647 +1,647 @@
1
- /**
2
- * dsh-preset-tuner 核心逻辑(纯函数 + 文件读写,不依赖任何 npm 包)。
3
- *
4
- * 设计原则:
5
- * 1. 只读上游:从 app 的 asar(或解包目录)里读出 shipped preset 声明原文。
6
- * 2. 只插入、不改写:生成的覆盖块 = 上游声明逐字节 + 我们注入的行。
7
- * 因此上游内容永远不会被我们篡改,升级后重新生成即可继承全部上游改动。
8
- * 3. 失败即放弃:抽取/校验任何一步不通过,就不写文件(宁可没效果,也不能弄坏启动)。
9
- * 4. 可回滚:每次写入前把原文件备份到 <profile>/dsh-preset-tuner/backups/。
10
- */
11
-
12
- import { createHash } from 'node:crypto'
13
- import {
14
- closeSync,
15
- copyFileSync,
16
- existsSync,
17
- mkdirSync,
18
- openSync,
19
- readFileSync,
20
- readSync,
21
- readdirSync,
22
- unlinkSync,
23
- writeFileSync,
24
- } from 'node:fs'
25
- import { homedir } from 'node:os'
26
- import { dirname, join, resolve } from 'node:path'
27
-
28
- export const MARK_BEGIN = '# >>> dsh-context-kit: managed block: '
29
- export const MARK_END = '# <<< dsh-context-kit: managed block: '
30
- /** 旧包名(dsh-preset-tuner)生成的块仍然要能识别,否则会被当成“外来覆盖”或再追加一份。 */
31
- export const LEGACY_MARK_BEGIN = '# >>> dsh-preset-tuner: managed block: '
32
- export const LEGACY_MARK_END = '# <<< dsh-preset-tuner: managed block: '
33
- export const PATCH_FILE = 'cordis.patch.yml'
34
- export const PRESETS_DIR = 'node_modules/@deepseek-ai/dsh-web-app/presets'
35
-
36
- const MARK_BEGIN_RE = /^# >>> (?:dsh-context-kit|dsh-preset-tuner): managed block: (.+?)\s*>>>\s*$/
37
- const isEndMarkerFor = (line, presetId) =>
38
- [MARK_END, LEGACY_MARK_END].some((prefix) => line.trim().startsWith(`${prefix}${presetId}`))
39
-
40
- const sha256 = (input) => createHash('sha256').update(input).digest('hex')
41
- export const shortSha = (input) => sha256(input).slice(0, 16)
42
-
43
- /* ────────────────────────────── asar 读取 ────────────────────────────── */
44
-
45
- /**
46
- * Electron 会把 .asar 当成目录来拦截 fs 调用,直接以文件打开会失败。
47
- * process.noAsar 是官方的绕过开关,读完立刻恢复原值。
48
- */
49
- function withoutAsarShim(fn) {
50
- const previous = process.noAsar
51
- try {
52
- process.noAsar = true
53
- return fn()
54
- } finally {
55
- process.noAsar = previous
56
- }
57
- }
58
-
59
- /** 打开 asar,解析头部索引。调用方负责 closeAsar。 */
60
- export function openAsar(archive) {
61
- const fd = withoutAsarShim(() => openSync(archive, 'r'))
62
- try {
63
- const head = Buffer.alloc(16)
64
- withoutAsarShim(() => readSync(fd, head, 0, 16, 0))
65
- const payloadSize = head.readUInt32LE(4)
66
- if (!payloadSize || payloadSize > 64 * 1024 * 1024) {
67
- throw new Error(`asar 头部长度异常: ${payloadSize}`)
68
- }
69
- const payload = Buffer.alloc(payloadSize)
70
- withoutAsarShim(() => readSync(fd, payload, 0, payloadSize, 8))
71
- const start = payload.indexOf('{"files"')
72
- if (start < 0) throw new Error('asar 头部找不到文件索引 JSON')
73
- const json = JSON.parse(payload.subarray(start).toString('utf8').replace(/\0+$/, ''))
74
- return { fd, base: 8 + payloadSize, json, archive }
75
- } catch (error) {
76
- closeSync(fd)
77
- throw error
78
- }
79
- }
80
-
81
- export function closeAsar(asar) {
82
- try {
83
- closeSync(asar.fd)
84
- } catch {}
85
- }
86
-
87
- function asarNode(asar, internalPath) {
88
- const parts = String(internalPath).replace(/\\/g, '/').split('/').filter(Boolean)
89
- let node = asar.json
90
- for (const part of parts) {
91
- node = node?.files?.[part]
92
- if (!node) return undefined
93
- }
94
- return node
95
- }
96
-
97
- /** 读 asar 内的文件;不存在或未打包返回 null。 */
98
- export function readAsarEntry(asar, internalPath) {
99
- const node = asarNode(asar, internalPath)
100
- if (!node || node.files || node.unpacked || typeof node.size !== 'number') return null
101
- const buffer = Buffer.alloc(node.size)
102
- withoutAsarShim(() => readSync(asar.fd, buffer, 0, node.size, asar.base + Number(node.offset)))
103
- return buffer
104
- }
105
-
106
- /** 列 asar 内的目录;不存在返回 []。 */
107
- export function listAsarDir(asar, internalDir) {
108
- const node = asarNode(asar, internalDir)
109
- if (!node?.files) return []
110
- return Object.entries(node.files)
111
- .filter(([, value]) => !value.files)
112
- .map(([name]) => name)
113
- }
114
-
115
- /* ─────────────────────────── app / 上游定位 ─────────────────────────── */
116
-
117
- const uniq = (list) => [...new Set(list.filter(Boolean).map((item) => resolve(item)))]
118
-
119
- /**
120
- * 找出所有可能的“上游来源”。按优先级:显式配置 → Electron resourcesPath →
121
- * 可执行文件旁边的 resources(普通 node 进程兜底)。
122
- */
123
- export function resolveAppSources({ config = {}, resourcesPath, execPath } = {}) {
124
- const roots = uniq([
125
- config.appRoot,
126
- resourcesPath,
127
- execPath ? join(dirname(execPath), 'resources') : undefined,
128
- ])
129
- const sources = []
130
- for (const root of roots) {
131
- const asar = join(root, 'app.asar')
132
- if (existsSync(asar)) sources.push({ kind: 'asar', path: asar, root })
133
- for (const name of ['app', 'app.asar.unpacked']) {
134
- const dir = join(root, name)
135
- if (existsSync(dir)) sources.push({ kind: 'dir', path: dir, root })
136
- }
137
- }
138
- return sources
139
- }
140
-
141
- /** 统一的读文件接口,asar 与目录两种来源都能用。 */
142
- export function readSourceFile(source, internalPath) {
143
- if (source.kind === 'dir') {
144
- const file = join(source.path, ...internalPath.split('/'))
145
- return existsSync(file) ? readFileSync(file) : null
146
- }
147
- const asar = openAsar(source.path)
148
- try {
149
- return readAsarEntry(asar, internalPath)
150
- } finally {
151
- closeAsar(asar)
152
- }
153
- }
154
-
155
- export function listSourceDir(source, internalDir) {
156
- if (source.kind === 'dir') {
157
- const dir = join(source.path, ...internalDir.split('/'))
158
- if (!existsSync(dir)) return []
159
- return readdirSync(dir, { withFileTypes: true })
160
- .filter((entry) => entry.isFile())
161
- .map((entry) => entry.name)
162
- }
163
- const asar = openAsar(source.path)
164
- try {
165
- return listAsarDir(asar, internalDir)
166
- } finally {
167
- closeAsar(asar)
168
- }
169
- }
170
-
171
- /**
172
- * 扫描所有来源,返回 presetId → { source, internalPath, text, sha }。
173
- * 同一 preset 出现在多个来源时,先出现的优先(asar 优先于解包目录)。
174
- * onError 用于把“读不到”的原因暴露给调用方(不要静默失败)。
175
- */
176
- export function discoverPresets(sources, { onError } = {}) {
177
- const report = (message) => {
178
- try {
179
- onError?.(message)
180
- } catch {}
181
- }
182
- const found = new Map()
183
- for (const source of sources) {
184
- let names = []
185
- try {
186
- names = listSourceDir(source, PRESETS_DIR)
187
- } catch (error) {
188
- report(`读取 ${source.kind}:${source.path} 的 presets 目录失败:${error?.message ?? error}`)
189
- continue
190
- }
191
- if (names.length === 0) continue
192
- for (const name of names) {
193
- const match = /^(.+)\.patch\.yml$/.exec(name)
194
- if (!match) continue
195
- const presetId = match[1]
196
- if (found.has(presetId)) continue
197
- const internalPath = `${PRESETS_DIR}/${name}`
198
- let buffer
199
- try {
200
- buffer = readSourceFile(source, internalPath)
201
- } catch (error) {
202
- report(`读取 ${internalPath} 失败:${error?.message ?? error}`)
203
- continue
204
- }
205
- if (!buffer) continue
206
- const text = buffer.toString('utf8')
207
- found.set(presetId, {
208
- presetId,
209
- source: `${source.kind === 'asar' ? 'app.asar' : source.path}`,
210
- internalPath,
211
- text,
212
- sha: shortSha(text),
213
- })
214
- }
215
- }
216
- return found
217
- }
218
-
219
- /* ─────────────────────────── YAML 文本切块 ─────────────────────────── */
220
-
221
- const indentOf = (line) => line.match(/^\s*/)[0].length
222
- const isBlank = (line) => line.trim() === ''
223
-
224
- /**
225
- * 从 shipped preset 文件里抽出 `- id: <presetId>` 这一整块,并按该块的
226
- * 起始缩进去掉公共缩进,得到可直接当作 profile 覆盖行使用的行数组。
227
- */
228
- export function extractDeclaration(text, presetId) {
229
- const lines = String(text).split(/\r?\n/)
230
- const wanted = `preset-${presetId}`
231
- const start = lines.findIndex((line) => {
232
- const match = /^\s*-\s+id:\s*(\S+)\s*$/.exec(line)
233
- return match?.[1] === wanted
234
- })
235
- if (start < 0) throw new Error(`上游声明里找不到 preset-${presetId}(文件名/实现可能已变)`)
236
- const indent = indentOf(lines[start])
237
- if (indent < 2) throw new Error(`preset-${presetId} 不是 insert 子项,格式与预期不符`)
238
-
239
- const out = []
240
- for (let i = start; i < lines.length; i += 1) {
241
- const line = lines[i]
242
- if (isBlank(line)) {
243
- out.push('')
244
- continue
245
- }
246
- const current = indentOf(line)
247
- if (current < indent) break
248
- out.push(line.slice(indent))
249
- }
250
- while (out.length > 0 && out[out.length - 1] === '') out.pop()
251
- if (out.length < 5) throw new Error(`preset-${presetId} 块内容过短,放弃处理`)
252
- return { lines: out, indent }
253
- }
254
-
255
- /** 找出声明里 `plugins:` 的列表项(顶层插件行)。 */
256
- export function pluginItems(lines) {
257
- const keyIdx = lines.findIndex((line) => /^\s*plugins:\s*$/.test(line))
258
- if (keyIdx < 0) throw new Error('声明里找不到 plugins: 列表')
259
- const keyIndent = indentOf(lines[keyIdx])
260
- const itemIndent = keyIndent + 2
261
- const items = []
262
- for (let i = keyIdx + 1; i < lines.length; i += 1) {
263
- const line = lines[i]
264
- if (isBlank(line)) continue
265
- const current = indentOf(line)
266
- if (current <= keyIndent) break
267
- if (current === itemIndent && /^-\s/.test(line.slice(current))) items.push(i)
268
- }
269
- if (items.length === 0) throw new Error('plugins 列表为空,放弃处理')
270
- return { keyIdx, keyIndent, itemIndent, items }
271
- }
272
-
273
- const idOfItem = (line) => {
274
- const match = /^\s*-\s+id:\s*(\S+)\s*$/.exec(line)
275
- return match?.[1]
276
- }
277
-
278
- /** 返回某个插件行在 lines 中的 [start, end) 区间。 */
279
- export function pluginRange(lines, items, pluginId) {
280
- const index = items.findIndex((lineIdx) => idOfItem(lines[lineIdx]) === pluginId)
281
- if (index < 0) return null
282
- const start = items[index]
283
- const end = index + 1 < items.length ? items[index + 1] : lines.length
284
- return { start, end }
285
- }
286
-
287
- /** YAML 标量渲染:只处理 v1 需要的布尔/数字/字符串。 */
288
- export function yamlScalar(value) {
289
- if (typeof value === 'boolean') return value ? 'true' : 'false'
290
- if (typeof value === 'number') {
291
- if (!Number.isFinite(value)) throw new Error(`不能写入非有限数字: ${value}`)
292
- return String(value)
293
- }
294
- if (value === null) return 'null'
295
- const text = String(value)
296
- if (text === '') return "''"
297
- // 裸标量必须以字母/数字/下划线开头:@ 和 ` 是 YAML 保留指示符,开头用它必须加引号。
298
- if (/^[A-Za-z0-9_][A-Za-z0-9_.@/-]*$/.test(text) && !/^(true|false|null|yes|no|on|off)$/i.test(text)) return text
299
- return `'${text.replace(/'/g, "''")}'`
300
- }
301
-
302
- /** 收集某个插件行已有的 config 标量键(用于冲突检测)。 */
303
- function existingConfigKeys(lines, range) {
304
- const { start, end } = range
305
- for (let i = start + 1; i < end; i += 1) {
306
- if (/^\s+config:\s*$/.test(lines[i])) {
307
- const configIndent = indentOf(lines[i])
308
- const keys = new Map()
309
- for (let j = i + 1; j < end; j += 1) {
310
- if (isBlank(lines[j])) continue
311
- const current = indentOf(lines[j])
312
- if (current <= configIndent) break
313
- if (current === configIndent + 2) {
314
- const match = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(lines[j].slice(current))
315
- if (match) keys.set(match[1], j)
316
- }
317
- }
318
- return { configIdx: i, configIndent, keys }
319
- }
320
- }
321
- return null
322
- }
323
-
324
- /**
325
- * 给某个预设插件注入 / 合并 config 键。
326
- * 只做插入;若上游已有同名键则抛错(拒绝静默覆盖上游值)。
327
- */
328
- /** 找出某个组行内部 config 列表的区间与列表项。 */
329
- export function groupItems(lines, groupId) {
330
- const { items, itemIndent } = pluginItems(lines)
331
- const range = pluginRange(lines, items, groupId)
332
- if (!range) throw new Error(`预设里找不到组 "${groupId}"`)
333
- let configIdx = -1
334
- let configIndent = 0
335
- for (let i = range.start + 1; i < range.end; i += 1) {
336
- if (/^\s+config:\s*$/.test(lines[i])) {
337
- configIdx = i
338
- configIndent = indentOf(lines[i])
339
- break
340
- }
341
- }
342
- if (configIdx < 0) throw new Error(`组 "${groupId}" 没有 config 列表,格式与预期不符`)
343
- const listIndent = configIndent + 2
344
- let listEnd = range.end
345
- for (let i = configIdx + 1; i < range.end; i += 1) {
346
- if (isBlank(lines[i])) continue
347
- if (indentOf(lines[i]) < listIndent) {
348
- listEnd = i
349
- break
350
- }
351
- }
352
- const listItems = []
353
- for (let i = configIdx + 1; i < listEnd; i += 1) {
354
- if (isBlank(lines[i])) continue
355
- if (indentOf(lines[i]) === listIndent && /^-\s/.test(lines[i].slice(listIndent))) listItems.push(i)
356
- }
357
- if (listItems.length === 0) throw new Error(`组 "${groupId}" 的 config 列表为空`)
358
- return { configIdx, configIndent, listIndent, listEnd, items: listItems, groupRange: range, topItemIndent: itemIndent }
359
- }
360
-
361
- /** group 为空时作用于预设顶层插件列表,否则作用于该组的 config 列表。 */
362
- function scopeOf(lines, group) {
363
- if (!group) {
364
- const { items, itemIndent } = pluginItems(lines)
365
- return { items, itemIndent, end: lines.length }
366
- }
367
- const info = groupItems(lines, group)
368
- return { items: info.items, itemIndent: info.listIndent, end: info.listEnd }
369
- }
370
-
371
- function rangeOf(lines, scope, pluginId) {
372
- const index = scope.items.findIndex((lineIdx) => idOfItem(lines[lineIdx]) === pluginId)
373
- if (index < 0) return null
374
- const start = scope.items[index]
375
- const end = index + 1 < scope.items.length ? scope.items[index + 1] : scope.end
376
- return { start, end }
377
- }
378
-
379
- /**
380
- * 给预设插件注入 / 合并 config 键。group 指定时在该组的 config 列表里找插件
381
- * (例如 compaction 组的 compaction-basic —— 隔离域里的插件只能按组定位)。
382
- * 只做插入;若上游已有同名键则抛错,拒绝静默覆盖上游值。
383
- */
384
- export function applyPluginConfig(lines, pluginId, config, { group } = {}) {
385
- const keys = Object.entries(config ?? {})
386
- const out = lines.slice()
387
- if (keys.length === 0) return out
388
- const scope = scopeOf(out, group)
389
- const range = rangeOf(out, scope, pluginId)
390
- if (!range) {
391
- throw new Error(`预设里找不到插件 "${pluginId}"${group ? `(组 ${group} 内)` : ''};上游可能改了 id`)
392
- }
393
- const itemIndent = scope.itemIndent
394
-
395
- const existing = existingConfigKeys(out, range)
396
- if (existing) {
397
- const conflicts = keys.filter(([key]) => existing.keys.has(key)).map(([key]) => key)
398
- if (conflicts.length > 0) {
399
- throw new Error(
400
- `上游 ${pluginId} 已显式设置 ${conflicts.join(', ')};为避免覆盖上游值,本次放弃写入(需人工合并)`,
401
- )
402
- }
403
- const insertAt = existing.configIdx + 1
404
- const pad = ' '.repeat(existing.configIndent + 2)
405
- out.splice(insertAt, 0, ...keys.map(([key, value]) => `${pad}${key}: ${yamlScalar(value)}`))
406
- return out
407
- }
408
-
409
- // 没有 config:紧跟 name: 行插入
410
- const nameIdx = out.findIndex((line, index) => index > range.start && index < range.end && /^\s+name:/.test(line))
411
- if (nameIdx < 0) throw new Error(`插件 ${pluginId} 缺少 name: 行,格式与预期不符`)
412
- const pad = ' '.repeat(itemIndent + 2)
413
- const keyPad = ' '.repeat(itemIndent + 4)
414
- out.splice(nameIdx + 1, 0, `${pad}config:`, ...keys.map(([key, value]) => `${keyPad}${key}: ${yamlScalar(value)}`))
415
- return out
416
- }
417
-
418
- /**
419
- * 往预设里新增一个插件行。group 指定时插入该组的 config 列表内部
420
- * (preset 内的隔离域是组的 realm,插在顶层拿不到组内服务)。
421
- */
422
- export function applyPluginAdd(lines, entry) {
423
- const out = lines.slice()
424
- const { items, itemIndent } = pluginItems(out)
425
- const render = (pad) => {
426
- const rows = [`${pad}- id: ${entry.id}`, `${pad} name: ${yamlScalar(entry.name)}`]
427
- const keys = Object.entries(entry.config ?? {})
428
- if (keys.length > 0) {
429
- rows.push(`${pad} config:`)
430
- for (const [key, value] of keys) rows.push(`${pad} ${key}: ${yamlScalar(value)}`)
431
- }
432
- return rows
433
- }
434
-
435
- if (!entry.group) {
436
- const last = items[items.length - 1]
437
- let end = out.length
438
- for (let i = last + 1; i < out.length; i += 1) {
439
- if (!isBlank(out[i]) && indentOf(out[i]) <= itemIndent) {
440
- end = i
441
- break
442
- }
443
- }
444
- out.splice(end, 0, ...render(' '.repeat(itemIndent)))
445
- return out
446
- }
447
-
448
- const groupInfo = groupItems(out, entry.group)
449
- out.splice(groupInfo.listEnd, 0, ...render(' '.repeat(groupInfo.listIndent)))
450
- return out
451
- }
452
-
453
- /**
454
- * 生成一个 preset 的覆盖声明行:上游原文 + 注入的改动。
455
- * 返回 { lines, added },added 记录注入位置,便于自检“除注入外逐字节相同”。
456
- */
457
- export function buildOverride(declarationLines, tweaks = {}) {
458
- let out = declarationLines.slice()
459
- const plugins = tweaks.plugins && typeof tweaks.plugins === 'object' ? tweaks.plugins : {}
460
- const adds = Array.isArray(tweaks.add) ? tweaks.add : []
461
-
462
- for (const [pluginId, spec] of Object.entries(plugins)) {
463
- const config = spec && typeof spec === 'object' && 'config' in spec ? spec.config : spec
464
- const group = spec && typeof spec === 'object' && typeof spec.group === 'string' ? spec.group : undefined
465
- out = applyPluginConfig(out, pluginId, config, { group })
466
- }
467
- for (const entry of adds) {
468
- if (!entry?.id || !entry?.name) throw new Error('add 条目必须有 id 与 name')
469
- out = applyPluginAdd(out, entry)
470
- }
471
- return out
472
- }
473
-
474
- /* ─────────────────────── managed block 拼接与解析 ─────────────────────── */
475
-
476
- export function renderBlock({ presetId, upstreamSha, upstreamPath, declarationLines, note }) {
477
- const header = [
478
- `${MARK_BEGIN}${presetId} >>>`,
479
- '# 本段由 dsh-context-kit 生成,请勿手工编辑。',
480
- '# 它 = 上游声明原文(逐字节保留)+ 本插件注入的少量行,因此上游升级后重新 sync 即可继承全部改动。',
481
- `# 上游: ${upstreamPath}`,
482
- `# 上游 sha256: ${upstreamSha}`,
483
- ]
484
- if (note) header.push(`# ${note}`)
485
- return [...header, ...declarationLines, `${MARK_END}${presetId} <<<`]
486
- }
487
-
488
- /** 解析现有文件里的 managed block,返回区间与元数据。 */
489
- export function parseManagedBlocks(text) {
490
- const lines = String(text ?? '').split(/\r?\n/)
491
- const blocks = []
492
- for (let i = 0; i < lines.length; i += 1) {
493
- const match = MARK_BEGIN_RE.exec(lines[i])
494
- if (!match) continue
495
- const presetId = match[1].trim()
496
- let end = -1
497
- for (let j = i + 1; j < lines.length; j += 1) {
498
- if (isEndMarkerFor(lines[j], presetId)) {
499
- end = j
500
- break
501
- }
502
- }
503
- if (end < 0) continue
504
- const body = lines.slice(i, end + 1)
505
- const shaLine = body.find((line) => /^#\s*上游 sha256:\s*(\S+)/.test(line))
506
- const pathLine = body.find((line) => /^#\s*上游:\s*(.+?)\s*$/.test(line))
507
- blocks.push({
508
- presetId,
509
- start: i,
510
- end,
511
- sha: shaLine ? /^#\s*上游 sha256:\s*(\S+)/.exec(shaLine)[1] : undefined,
512
- upstreamPath: pathLine ? /^#\s*上游:\s*(.+?)\s*$/.exec(pathLine)[1] : undefined,
513
- text: body.join('\n'),
514
- })
515
- i = end
516
- }
517
- return blocks
518
- }
519
-
520
- /** 找出 managed block 之外、与目标 preset 同 id 的顶层行(视为“外来覆盖”)。 */
521
- export function findForeignRows(text, presetId) {
522
- const lines = String(text ?? '').split(/\r?\n/)
523
- const managed = parseManagedBlocks(text)
524
- const inside = new Set()
525
- for (const block of managed) for (let i = block.start; i <= block.end; i += 1) inside.add(i)
526
- const wanted = `preset-${presetId}`
527
- const hits = []
528
- for (let i = 0; i < lines.length; i += 1) {
529
- if (inside.has(i)) continue
530
- const match = /^-\s+id:\s*(\S+)\s*$/.exec(lines[i])
531
- if (match?.[1] === wanted) hits.push(i)
532
- }
533
- return hits
534
- }
535
-
536
- /**
537
- * 用一个或多个 managed block 替换文件里已有的 block 区段。
538
- * blocks 为空 = 删除全部 managed block(clear)。
539
- */
540
- export function spliceBlocks(text, blocks) {
541
- const source = String(text ?? '')
542
- const lines = source.split(/\r?\n/)
543
- const existing = parseManagedBlocks(source)
544
- const kept = []
545
- let i = 0
546
- while (i < lines.length) {
547
- const block = existing.find((item) => item.start === i)
548
- if (block) {
549
- i = block.end + 1
550
- continue
551
- }
552
- kept.push(lines[i])
553
- i += 1
554
- }
555
- while (kept.length > 0 && isBlank(kept[kept.length - 1])) kept.pop()
556
- const rendered = blocks.flatMap((block) => ['', ...block])
557
- const out = [...kept, ...rendered]
558
- while (out.length > 0 && isBlank(out[out.length - 1])) out.pop()
559
- return `${out.join('\n')}\n`
560
- }
561
-
562
- /* ───────────────────────────── 结构与安全校验 ───────────────────────────── */
563
-
564
- /** 轻量结构校验:不引 YAML 解析器,只查会让 Loader 直接失败的形态。 */
565
- export function checkPatchShape(text) {
566
- const problems = []
567
- const lines = String(text ?? '').split(/\r?\n/)
568
- for (let i = 0; i < lines.length; i += 1) {
569
- if (lines[i].includes('\t')) problems.push(`第 ${i + 1} 行含制表符`)
570
- }
571
- const blocks = parseManagedBlocks(text)
572
- for (const block of blocks) {
573
- if (block.end <= block.start) problems.push(`${block.presetId} 区段没有结束标记`)
574
- const body = lines.slice(block.start, block.end + 1)
575
- const ids = body.filter((line) => /^\s+-\s+id:/.test(line)).length
576
- if (ids === 0) problems.push(`${block.presetId} 区段里没有插件行`)
577
- }
578
- const starts = (text.match(/^# >>> (?:dsh-context-kit|dsh-preset-tuner): managed block:/gm) ?? []).length
579
- const ends = (text.match(/^# <<< (?:dsh-context-kit|dsh-preset-tuner): managed block:/gm) ?? []).length
580
- if (starts !== ends) problems.push(`标记不配对(begin ${starts} / end ${ends})`)
581
- return problems
582
- }
583
-
584
- /** 备份 -> 写入。返回 { changed, backup, path }。 */
585
- export function writePatchFile(profileDir, text, { keepBackups = 10 } = {}) {
586
- const file = join(profileDir, PATCH_FILE)
587
- const previous = existsSync(file) ? readFileSync(file, 'utf8') : ''
588
- if (previous === text) return { changed: false, path: file, backup: null }
589
-
590
- const eol = previous.includes('\r\n') ? '\r\n' : '\n'
591
- const payload = eol === '\n' ? text : text.replace(/\r?\n/g, '\r\n')
592
- let backup = null
593
- if (previous) {
594
- const dir = join(profileDir, 'dsh-context-kit', 'backups')
595
- mkdirSync(dir, { recursive: true })
596
- const stamp = new Date().toISOString().replace(/[:.]/g, '-')
597
- backup = join(dir, `${PATCH_FILE}.${stamp}.bak`)
598
- copyFileSync(file, backup)
599
- const old = readdirSync(dir)
600
- .filter((name) => name.endsWith('.bak'))
601
- .sort()
602
- for (const name of old.slice(0, Math.max(0, old.length - keepBackups))) {
603
- try {
604
- unlinkSync(join(dir, name))
605
- } catch {}
606
- }
607
- }
608
- mkdirSync(profileDir, { recursive: true })
609
- writeFileSync(file, payload, 'utf8')
610
- return { changed: true, path: file, backup }
611
- }
612
-
613
- /* ─────────────────────────── profile 目录定位 ─────────────────────────── */
614
-
615
- /**
616
- * 定位 profile 目录。顺序:显式配置 → 环境变量 → 模块自身安装路径 →
617
- * ~/.dsh/profiles/<配置名或 desktop> → 唯一 profile 兜底。
618
- */
619
- export function resolveProfileDir({ config = {}, moduleUrl, home = homedir(), env = process.env } = {}) {
620
- if (config.profileDir) return { dir: resolve(config.profileDir), via: 'config.profileDir' }
621
- if (env.DSH_PROFILE_DIR) return { dir: resolve(env.DSH_PROFILE_DIR), via: 'env.DSH_PROFILE_DIR' }
622
-
623
- if (moduleUrl) {
624
- const match = /[\\/]profiles[\\/]([^\\/]+)[\\/]/.exec(moduleUrl)
625
- if (match) {
626
- const base = env.DSH_HOME ? resolve(env.DSH_HOME) : join(home, '.dsh')
627
- const candidate = join(base, 'profiles', match[1])
628
- if (existsSync(candidate)) return { dir: candidate, via: 'module path' }
629
- }
630
- }
631
-
632
- const base = env.DSH_HOME ? resolve(env.DSH_HOME) : join(home, '.dsh')
633
- const preferred = join(base, 'profiles', config.profile ?? 'desktop')
634
- if (existsSync(preferred)) return { dir: preferred, via: `profiles/${config.profile ?? 'desktop'}` }
635
-
636
- const root = join(base, 'profiles')
637
- if (existsSync(root)) {
638
- const names = readdirSync(root, { withFileTypes: true })
639
- .filter((entry) => entry.isDirectory() && entry.name !== 'node_modules')
640
- .map((entry) => entry.name)
641
- if (names.length === 1) return { dir: join(root, names[0]), via: '唯一 profile' }
642
- if (names.length > 1) {
643
- throw new Error(`找到多个 profile(${names.join(', ')}),请在插件配置里显式设置 profileDir`)
644
- }
645
- }
646
- throw new Error('找不到 DSH profile 目录,请在插件配置里设置 profileDir')
647
- }
1
+ /**
2
+ * dsh-preset-tuner 核心逻辑(纯函数 + 文件读写,不依赖任何 npm 包)。
3
+ *
4
+ * 设计原则:
5
+ * 1. 只读上游:从 app 的 asar(或解包目录)里读出 shipped preset 声明原文。
6
+ * 2. 只插入、不改写:生成的覆盖块 = 上游声明逐字节 + 我们注入的行。
7
+ * 因此上游内容永远不会被我们篡改,升级后重新生成即可继承全部上游改动。
8
+ * 3. 失败即放弃:抽取/校验任何一步不通过,就不写文件(宁可没效果,也不能弄坏启动)。
9
+ * 4. 可回滚:每次写入前把原文件备份到 <profile>/dsh-preset-tuner/backups/。
10
+ */
11
+
12
+ import { createHash } from 'node:crypto'
13
+ import {
14
+ closeSync,
15
+ copyFileSync,
16
+ existsSync,
17
+ mkdirSync,
18
+ openSync,
19
+ readFileSync,
20
+ readSync,
21
+ readdirSync,
22
+ unlinkSync,
23
+ writeFileSync,
24
+ } from 'node:fs'
25
+ import { homedir } from 'node:os'
26
+ import { dirname, join, resolve } from 'node:path'
27
+
28
+ export const MARK_BEGIN = '# >>> dsh-context-kit: managed block: '
29
+ export const MARK_END = '# <<< dsh-context-kit: managed block: '
30
+ /** 旧包名(dsh-preset-tuner)生成的块仍然要能识别,否则会被当成“外来覆盖”或再追加一份。 */
31
+ export const LEGACY_MARK_BEGIN = '# >>> dsh-preset-tuner: managed block: '
32
+ export const LEGACY_MARK_END = '# <<< dsh-preset-tuner: managed block: '
33
+ export const PATCH_FILE = 'cordis.patch.yml'
34
+ export const PRESETS_DIR = 'node_modules/@deepseek-ai/dsh-web-app/presets'
35
+
36
+ const MARK_BEGIN_RE = /^# >>> (?:dsh-context-kit|dsh-preset-tuner): managed block: (.+?)\s*>>>\s*$/
37
+ const isEndMarkerFor = (line, presetId) =>
38
+ [MARK_END, LEGACY_MARK_END].some((prefix) => line.trim().startsWith(`${prefix}${presetId}`))
39
+
40
+ const sha256 = (input) => createHash('sha256').update(input).digest('hex')
41
+ export const shortSha = (input) => sha256(input).slice(0, 16)
42
+
43
+ /* ────────────────────────────── asar 读取 ────────────────────────────── */
44
+
45
+ /**
46
+ * Electron 会把 .asar 当成目录来拦截 fs 调用,直接以文件打开会失败。
47
+ * process.noAsar 是官方的绕过开关,读完立刻恢复原值。
48
+ */
49
+ function withoutAsarShim(fn) {
50
+ const previous = process.noAsar
51
+ try {
52
+ process.noAsar = true
53
+ return fn()
54
+ } finally {
55
+ process.noAsar = previous
56
+ }
57
+ }
58
+
59
+ /** 打开 asar,解析头部索引。调用方负责 closeAsar。 */
60
+ export function openAsar(archive) {
61
+ const fd = withoutAsarShim(() => openSync(archive, 'r'))
62
+ try {
63
+ const head = Buffer.alloc(16)
64
+ withoutAsarShim(() => readSync(fd, head, 0, 16, 0))
65
+ const payloadSize = head.readUInt32LE(4)
66
+ if (!payloadSize || payloadSize > 64 * 1024 * 1024) {
67
+ throw new Error(`asar 头部长度异常: ${payloadSize}`)
68
+ }
69
+ const payload = Buffer.alloc(payloadSize)
70
+ withoutAsarShim(() => readSync(fd, payload, 0, payloadSize, 8))
71
+ const start = payload.indexOf('{"files"')
72
+ if (start < 0) throw new Error('asar 头部找不到文件索引 JSON')
73
+ const json = JSON.parse(payload.subarray(start).toString('utf8').replace(/\0+$/, ''))
74
+ return { fd, base: 8 + payloadSize, json, archive }
75
+ } catch (error) {
76
+ closeSync(fd)
77
+ throw error
78
+ }
79
+ }
80
+
81
+ export function closeAsar(asar) {
82
+ try {
83
+ closeSync(asar.fd)
84
+ } catch {}
85
+ }
86
+
87
+ function asarNode(asar, internalPath) {
88
+ const parts = String(internalPath).replace(/\\/g, '/').split('/').filter(Boolean)
89
+ let node = asar.json
90
+ for (const part of parts) {
91
+ node = node?.files?.[part]
92
+ if (!node) return undefined
93
+ }
94
+ return node
95
+ }
96
+
97
+ /** 读 asar 内的文件;不存在或未打包返回 null。 */
98
+ export function readAsarEntry(asar, internalPath) {
99
+ const node = asarNode(asar, internalPath)
100
+ if (!node || node.files || node.unpacked || typeof node.size !== 'number') return null
101
+ const buffer = Buffer.alloc(node.size)
102
+ withoutAsarShim(() => readSync(asar.fd, buffer, 0, node.size, asar.base + Number(node.offset)))
103
+ return buffer
104
+ }
105
+
106
+ /** 列 asar 内的目录;不存在返回 []。 */
107
+ export function listAsarDir(asar, internalDir) {
108
+ const node = asarNode(asar, internalDir)
109
+ if (!node?.files) return []
110
+ return Object.entries(node.files)
111
+ .filter(([, value]) => !value.files)
112
+ .map(([name]) => name)
113
+ }
114
+
115
+ /* ─────────────────────────── app / 上游定位 ─────────────────────────── */
116
+
117
+ const uniq = (list) => [...new Set(list.filter(Boolean).map((item) => resolve(item)))]
118
+
119
+ /**
120
+ * 找出所有可能的“上游来源”。按优先级:显式配置 → Electron resourcesPath →
121
+ * 可执行文件旁边的 resources(普通 node 进程兜底)。
122
+ */
123
+ export function resolveAppSources({ config = {}, resourcesPath, execPath } = {}) {
124
+ const roots = uniq([
125
+ config.appRoot,
126
+ resourcesPath,
127
+ execPath ? join(dirname(execPath), 'resources') : undefined,
128
+ ])
129
+ const sources = []
130
+ for (const root of roots) {
131
+ const asar = join(root, 'app.asar')
132
+ if (existsSync(asar)) sources.push({ kind: 'asar', path: asar, root })
133
+ for (const name of ['app', 'app.asar.unpacked']) {
134
+ const dir = join(root, name)
135
+ if (existsSync(dir)) sources.push({ kind: 'dir', path: dir, root })
136
+ }
137
+ }
138
+ return sources
139
+ }
140
+
141
+ /** 统一的读文件接口,asar 与目录两种来源都能用。 */
142
+ export function readSourceFile(source, internalPath) {
143
+ if (source.kind === 'dir') {
144
+ const file = join(source.path, ...internalPath.split('/'))
145
+ return existsSync(file) ? readFileSync(file) : null
146
+ }
147
+ const asar = openAsar(source.path)
148
+ try {
149
+ return readAsarEntry(asar, internalPath)
150
+ } finally {
151
+ closeAsar(asar)
152
+ }
153
+ }
154
+
155
+ export function listSourceDir(source, internalDir) {
156
+ if (source.kind === 'dir') {
157
+ const dir = join(source.path, ...internalDir.split('/'))
158
+ if (!existsSync(dir)) return []
159
+ return readdirSync(dir, { withFileTypes: true })
160
+ .filter((entry) => entry.isFile())
161
+ .map((entry) => entry.name)
162
+ }
163
+ const asar = openAsar(source.path)
164
+ try {
165
+ return listAsarDir(asar, internalDir)
166
+ } finally {
167
+ closeAsar(asar)
168
+ }
169
+ }
170
+
171
+ /**
172
+ * 扫描所有来源,返回 presetId → { source, internalPath, text, sha }。
173
+ * 同一 preset 出现在多个来源时,先出现的优先(asar 优先于解包目录)。
174
+ * onError 用于把“读不到”的原因暴露给调用方(不要静默失败)。
175
+ */
176
+ export function discoverPresets(sources, { onError } = {}) {
177
+ const report = (message) => {
178
+ try {
179
+ onError?.(message)
180
+ } catch {}
181
+ }
182
+ const found = new Map()
183
+ for (const source of sources) {
184
+ let names = []
185
+ try {
186
+ names = listSourceDir(source, PRESETS_DIR)
187
+ } catch (error) {
188
+ report(`读取 ${source.kind}:${source.path} 的 presets 目录失败:${error?.message ?? error}`)
189
+ continue
190
+ }
191
+ if (names.length === 0) continue
192
+ for (const name of names) {
193
+ const match = /^(.+)\.patch\.yml$/.exec(name)
194
+ if (!match) continue
195
+ const presetId = match[1]
196
+ if (found.has(presetId)) continue
197
+ const internalPath = `${PRESETS_DIR}/${name}`
198
+ let buffer
199
+ try {
200
+ buffer = readSourceFile(source, internalPath)
201
+ } catch (error) {
202
+ report(`读取 ${internalPath} 失败:${error?.message ?? error}`)
203
+ continue
204
+ }
205
+ if (!buffer) continue
206
+ const text = buffer.toString('utf8')
207
+ found.set(presetId, {
208
+ presetId,
209
+ source: `${source.kind === 'asar' ? 'app.asar' : source.path}`,
210
+ internalPath,
211
+ text,
212
+ sha: shortSha(text),
213
+ })
214
+ }
215
+ }
216
+ return found
217
+ }
218
+
219
+ /* ─────────────────────────── YAML 文本切块 ─────────────────────────── */
220
+
221
+ const indentOf = (line) => line.match(/^\s*/)[0].length
222
+ const isBlank = (line) => line.trim() === ''
223
+
224
+ /**
225
+ * 从 shipped preset 文件里抽出 `- id: <presetId>` 这一整块,并按该块的
226
+ * 起始缩进去掉公共缩进,得到可直接当作 profile 覆盖行使用的行数组。
227
+ */
228
+ export function extractDeclaration(text, presetId) {
229
+ const lines = String(text).split(/\r?\n/)
230
+ const wanted = `preset-${presetId}`
231
+ const start = lines.findIndex((line) => {
232
+ const match = /^\s*-\s+id:\s*(\S+)\s*$/.exec(line)
233
+ return match?.[1] === wanted
234
+ })
235
+ if (start < 0) throw new Error(`上游声明里找不到 preset-${presetId}(文件名/实现可能已变)`)
236
+ const indent = indentOf(lines[start])
237
+ if (indent < 2) throw new Error(`preset-${presetId} 不是 insert 子项,格式与预期不符`)
238
+
239
+ const out = []
240
+ for (let i = start; i < lines.length; i += 1) {
241
+ const line = lines[i]
242
+ if (isBlank(line)) {
243
+ out.push('')
244
+ continue
245
+ }
246
+ const current = indentOf(line)
247
+ if (current < indent) break
248
+ out.push(line.slice(indent))
249
+ }
250
+ while (out.length > 0 && out[out.length - 1] === '') out.pop()
251
+ if (out.length < 5) throw new Error(`preset-${presetId} 块内容过短,放弃处理`)
252
+ return { lines: out, indent }
253
+ }
254
+
255
+ /** 找出声明里 `plugins:` 的列表项(顶层插件行)。 */
256
+ export function pluginItems(lines) {
257
+ const keyIdx = lines.findIndex((line) => /^\s*plugins:\s*$/.test(line))
258
+ if (keyIdx < 0) throw new Error('声明里找不到 plugins: 列表')
259
+ const keyIndent = indentOf(lines[keyIdx])
260
+ const itemIndent = keyIndent + 2
261
+ const items = []
262
+ for (let i = keyIdx + 1; i < lines.length; i += 1) {
263
+ const line = lines[i]
264
+ if (isBlank(line)) continue
265
+ const current = indentOf(line)
266
+ if (current <= keyIndent) break
267
+ if (current === itemIndent && /^-\s/.test(line.slice(current))) items.push(i)
268
+ }
269
+ if (items.length === 0) throw new Error('plugins 列表为空,放弃处理')
270
+ return { keyIdx, keyIndent, itemIndent, items }
271
+ }
272
+
273
+ const idOfItem = (line) => {
274
+ const match = /^\s*-\s+id:\s*(\S+)\s*$/.exec(line)
275
+ return match?.[1]
276
+ }
277
+
278
+ /** 返回某个插件行在 lines 中的 [start, end) 区间。 */
279
+ export function pluginRange(lines, items, pluginId) {
280
+ const index = items.findIndex((lineIdx) => idOfItem(lines[lineIdx]) === pluginId)
281
+ if (index < 0) return null
282
+ const start = items[index]
283
+ const end = index + 1 < items.length ? items[index + 1] : lines.length
284
+ return { start, end }
285
+ }
286
+
287
+ /** YAML 标量渲染:只处理 v1 需要的布尔/数字/字符串。 */
288
+ export function yamlScalar(value) {
289
+ if (typeof value === 'boolean') return value ? 'true' : 'false'
290
+ if (typeof value === 'number') {
291
+ if (!Number.isFinite(value)) throw new Error(`不能写入非有限数字: ${value}`)
292
+ return String(value)
293
+ }
294
+ if (value === null) return 'null'
295
+ const text = String(value)
296
+ if (text === '') return "''"
297
+ // 裸标量必须以字母/数字/下划线开头:@ 和 ` 是 YAML 保留指示符,开头用它必须加引号。
298
+ if (/^[A-Za-z0-9_][A-Za-z0-9_.@/-]*$/.test(text) && !/^(true|false|null|yes|no|on|off)$/i.test(text)) return text
299
+ return `'${text.replace(/'/g, "''")}'`
300
+ }
301
+
302
+ /** 收集某个插件行已有的 config 标量键(用于冲突检测)。 */
303
+ function existingConfigKeys(lines, range) {
304
+ const { start, end } = range
305
+ for (let i = start + 1; i < end; i += 1) {
306
+ if (/^\s+config:\s*$/.test(lines[i])) {
307
+ const configIndent = indentOf(lines[i])
308
+ const keys = new Map()
309
+ for (let j = i + 1; j < end; j += 1) {
310
+ if (isBlank(lines[j])) continue
311
+ const current = indentOf(lines[j])
312
+ if (current <= configIndent) break
313
+ if (current === configIndent + 2) {
314
+ const match = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(lines[j].slice(current))
315
+ if (match) keys.set(match[1], j)
316
+ }
317
+ }
318
+ return { configIdx: i, configIndent, keys }
319
+ }
320
+ }
321
+ return null
322
+ }
323
+
324
+ /**
325
+ * 给某个预设插件注入 / 合并 config 键。
326
+ * 只做插入;若上游已有同名键则抛错(拒绝静默覆盖上游值)。
327
+ */
328
+ /** 找出某个组行内部 config 列表的区间与列表项。 */
329
+ export function groupItems(lines, groupId) {
330
+ const { items, itemIndent } = pluginItems(lines)
331
+ const range = pluginRange(lines, items, groupId)
332
+ if (!range) throw new Error(`预设里找不到组 "${groupId}"`)
333
+ let configIdx = -1
334
+ let configIndent = 0
335
+ for (let i = range.start + 1; i < range.end; i += 1) {
336
+ if (/^\s+config:\s*$/.test(lines[i])) {
337
+ configIdx = i
338
+ configIndent = indentOf(lines[i])
339
+ break
340
+ }
341
+ }
342
+ if (configIdx < 0) throw new Error(`组 "${groupId}" 没有 config 列表,格式与预期不符`)
343
+ const listIndent = configIndent + 2
344
+ let listEnd = range.end
345
+ for (let i = configIdx + 1; i < range.end; i += 1) {
346
+ if (isBlank(lines[i])) continue
347
+ if (indentOf(lines[i]) < listIndent) {
348
+ listEnd = i
349
+ break
350
+ }
351
+ }
352
+ const listItems = []
353
+ for (let i = configIdx + 1; i < listEnd; i += 1) {
354
+ if (isBlank(lines[i])) continue
355
+ if (indentOf(lines[i]) === listIndent && /^-\s/.test(lines[i].slice(listIndent))) listItems.push(i)
356
+ }
357
+ if (listItems.length === 0) throw new Error(`组 "${groupId}" 的 config 列表为空`)
358
+ return { configIdx, configIndent, listIndent, listEnd, items: listItems, groupRange: range, topItemIndent: itemIndent }
359
+ }
360
+
361
+ /** group 为空时作用于预设顶层插件列表,否则作用于该组的 config 列表。 */
362
+ function scopeOf(lines, group) {
363
+ if (!group) {
364
+ const { items, itemIndent } = pluginItems(lines)
365
+ return { items, itemIndent, end: lines.length }
366
+ }
367
+ const info = groupItems(lines, group)
368
+ return { items: info.items, itemIndent: info.listIndent, end: info.listEnd }
369
+ }
370
+
371
+ function rangeOf(lines, scope, pluginId) {
372
+ const index = scope.items.findIndex((lineIdx) => idOfItem(lines[lineIdx]) === pluginId)
373
+ if (index < 0) return null
374
+ const start = scope.items[index]
375
+ const end = index + 1 < scope.items.length ? scope.items[index + 1] : scope.end
376
+ return { start, end }
377
+ }
378
+
379
+ /**
380
+ * 给预设插件注入 / 合并 config 键。group 指定时在该组的 config 列表里找插件
381
+ * (例如 compaction 组的 compaction-basic —— 隔离域里的插件只能按组定位)。
382
+ * 只做插入;若上游已有同名键则抛错,拒绝静默覆盖上游值。
383
+ */
384
+ export function applyPluginConfig(lines, pluginId, config, { group } = {}) {
385
+ const keys = Object.entries(config ?? {})
386
+ const out = lines.slice()
387
+ if (keys.length === 0) return out
388
+ const scope = scopeOf(out, group)
389
+ const range = rangeOf(out, scope, pluginId)
390
+ if (!range) {
391
+ throw new Error(`预设里找不到插件 "${pluginId}"${group ? `(组 ${group} 内)` : ''};上游可能改了 id`)
392
+ }
393
+ const itemIndent = scope.itemIndent
394
+
395
+ const existing = existingConfigKeys(out, range)
396
+ if (existing) {
397
+ const conflicts = keys.filter(([key]) => existing.keys.has(key)).map(([key]) => key)
398
+ if (conflicts.length > 0) {
399
+ throw new Error(
400
+ `上游 ${pluginId} 已显式设置 ${conflicts.join(', ')};为避免覆盖上游值,本次放弃写入(需人工合并)`,
401
+ )
402
+ }
403
+ const insertAt = existing.configIdx + 1
404
+ const pad = ' '.repeat(existing.configIndent + 2)
405
+ out.splice(insertAt, 0, ...keys.map(([key, value]) => `${pad}${key}: ${yamlScalar(value)}`))
406
+ return out
407
+ }
408
+
409
+ // 没有 config:紧跟 name: 行插入
410
+ const nameIdx = out.findIndex((line, index) => index > range.start && index < range.end && /^\s+name:/.test(line))
411
+ if (nameIdx < 0) throw new Error(`插件 ${pluginId} 缺少 name: 行,格式与预期不符`)
412
+ const pad = ' '.repeat(itemIndent + 2)
413
+ const keyPad = ' '.repeat(itemIndent + 4)
414
+ out.splice(nameIdx + 1, 0, `${pad}config:`, ...keys.map(([key, value]) => `${keyPad}${key}: ${yamlScalar(value)}`))
415
+ return out
416
+ }
417
+
418
+ /**
419
+ * 往预设里新增一个插件行。group 指定时插入该组的 config 列表内部
420
+ * (preset 内的隔离域是组的 realm,插在顶层拿不到组内服务)。
421
+ */
422
+ export function applyPluginAdd(lines, entry) {
423
+ const out = lines.slice()
424
+ const { items, itemIndent } = pluginItems(out)
425
+ const render = (pad) => {
426
+ const rows = [`${pad}- id: ${entry.id}`, `${pad} name: ${yamlScalar(entry.name)}`]
427
+ const keys = Object.entries(entry.config ?? {})
428
+ if (keys.length > 0) {
429
+ rows.push(`${pad} config:`)
430
+ for (const [key, value] of keys) rows.push(`${pad} ${key}: ${yamlScalar(value)}`)
431
+ }
432
+ return rows
433
+ }
434
+
435
+ if (!entry.group) {
436
+ const last = items[items.length - 1]
437
+ let end = out.length
438
+ for (let i = last + 1; i < out.length; i += 1) {
439
+ if (!isBlank(out[i]) && indentOf(out[i]) <= itemIndent) {
440
+ end = i
441
+ break
442
+ }
443
+ }
444
+ out.splice(end, 0, ...render(' '.repeat(itemIndent)))
445
+ return out
446
+ }
447
+
448
+ const groupInfo = groupItems(out, entry.group)
449
+ out.splice(groupInfo.listEnd, 0, ...render(' '.repeat(groupInfo.listIndent)))
450
+ return out
451
+ }
452
+
453
+ /**
454
+ * 生成一个 preset 的覆盖声明行:上游原文 + 注入的改动。
455
+ * 返回 { lines, added },added 记录注入位置,便于自检“除注入外逐字节相同”。
456
+ */
457
+ export function buildOverride(declarationLines, tweaks = {}) {
458
+ let out = declarationLines.slice()
459
+ const plugins = tweaks.plugins && typeof tweaks.plugins === 'object' ? tweaks.plugins : {}
460
+ const adds = Array.isArray(tweaks.add) ? tweaks.add : []
461
+
462
+ for (const [pluginId, spec] of Object.entries(plugins)) {
463
+ const config = spec && typeof spec === 'object' && 'config' in spec ? spec.config : spec
464
+ const group = spec && typeof spec === 'object' && typeof spec.group === 'string' ? spec.group : undefined
465
+ out = applyPluginConfig(out, pluginId, config, { group })
466
+ }
467
+ for (const entry of adds) {
468
+ if (!entry?.id || !entry?.name) throw new Error('add 条目必须有 id 与 name')
469
+ out = applyPluginAdd(out, entry)
470
+ }
471
+ return out
472
+ }
473
+
474
+ /* ─────────────────────── managed block 拼接与解析 ─────────────────────── */
475
+
476
+ export function renderBlock({ presetId, upstreamSha, upstreamPath, declarationLines, note }) {
477
+ const header = [
478
+ `${MARK_BEGIN}${presetId} >>>`,
479
+ '# 本段由 dsh-context-kit 生成,请勿手工编辑。',
480
+ '# 它 = 上游声明原文(逐字节保留)+ 本插件注入的少量行,因此上游升级后重新 sync 即可继承全部改动。',
481
+ `# 上游: ${upstreamPath}`,
482
+ `# 上游 sha256: ${upstreamSha}`,
483
+ ]
484
+ if (note) header.push(`# ${note}`)
485
+ return [...header, ...declarationLines, `${MARK_END}${presetId} <<<`]
486
+ }
487
+
488
+ /** 解析现有文件里的 managed block,返回区间与元数据。 */
489
+ export function parseManagedBlocks(text) {
490
+ const lines = String(text ?? '').split(/\r?\n/)
491
+ const blocks = []
492
+ for (let i = 0; i < lines.length; i += 1) {
493
+ const match = MARK_BEGIN_RE.exec(lines[i])
494
+ if (!match) continue
495
+ const presetId = match[1].trim()
496
+ let end = -1
497
+ for (let j = i + 1; j < lines.length; j += 1) {
498
+ if (isEndMarkerFor(lines[j], presetId)) {
499
+ end = j
500
+ break
501
+ }
502
+ }
503
+ if (end < 0) continue
504
+ const body = lines.slice(i, end + 1)
505
+ const shaLine = body.find((line) => /^#\s*上游 sha256:\s*(\S+)/.test(line))
506
+ const pathLine = body.find((line) => /^#\s*上游:\s*(.+?)\s*$/.test(line))
507
+ blocks.push({
508
+ presetId,
509
+ start: i,
510
+ end,
511
+ sha: shaLine ? /^#\s*上游 sha256:\s*(\S+)/.exec(shaLine)[1] : undefined,
512
+ upstreamPath: pathLine ? /^#\s*上游:\s*(.+?)\s*$/.exec(pathLine)[1] : undefined,
513
+ text: body.join('\n'),
514
+ })
515
+ i = end
516
+ }
517
+ return blocks
518
+ }
519
+
520
+ /** 找出 managed block 之外、与目标 preset 同 id 的顶层行(视为“外来覆盖”)。 */
521
+ export function findForeignRows(text, presetId) {
522
+ const lines = String(text ?? '').split(/\r?\n/)
523
+ const managed = parseManagedBlocks(text)
524
+ const inside = new Set()
525
+ for (const block of managed) for (let i = block.start; i <= block.end; i += 1) inside.add(i)
526
+ const wanted = `preset-${presetId}`
527
+ const hits = []
528
+ for (let i = 0; i < lines.length; i += 1) {
529
+ if (inside.has(i)) continue
530
+ const match = /^-\s+id:\s*(\S+)\s*$/.exec(lines[i])
531
+ if (match?.[1] === wanted) hits.push(i)
532
+ }
533
+ return hits
534
+ }
535
+
536
+ /**
537
+ * 用一个或多个 managed block 替换文件里已有的 block 区段。
538
+ * blocks 为空 = 删除全部 managed block(clear)。
539
+ */
540
+ export function spliceBlocks(text, blocks) {
541
+ const source = String(text ?? '')
542
+ const lines = source.split(/\r?\n/)
543
+ const existing = parseManagedBlocks(source)
544
+ const kept = []
545
+ let i = 0
546
+ while (i < lines.length) {
547
+ const block = existing.find((item) => item.start === i)
548
+ if (block) {
549
+ i = block.end + 1
550
+ continue
551
+ }
552
+ kept.push(lines[i])
553
+ i += 1
554
+ }
555
+ while (kept.length > 0 && isBlank(kept[kept.length - 1])) kept.pop()
556
+ const rendered = blocks.flatMap((block) => ['', ...block])
557
+ const out = [...kept, ...rendered]
558
+ while (out.length > 0 && isBlank(out[out.length - 1])) out.pop()
559
+ return `${out.join('\n')}\n`
560
+ }
561
+
562
+ /* ───────────────────────────── 结构与安全校验 ───────────────────────────── */
563
+
564
+ /** 轻量结构校验:不引 YAML 解析器,只查会让 Loader 直接失败的形态。 */
565
+ export function checkPatchShape(text) {
566
+ const problems = []
567
+ const lines = String(text ?? '').split(/\r?\n/)
568
+ for (let i = 0; i < lines.length; i += 1) {
569
+ if (lines[i].includes('\t')) problems.push(`第 ${i + 1} 行含制表符`)
570
+ }
571
+ const blocks = parseManagedBlocks(text)
572
+ for (const block of blocks) {
573
+ if (block.end <= block.start) problems.push(`${block.presetId} 区段没有结束标记`)
574
+ const body = lines.slice(block.start, block.end + 1)
575
+ const ids = body.filter((line) => /^\s+-\s+id:/.test(line)).length
576
+ if (ids === 0) problems.push(`${block.presetId} 区段里没有插件行`)
577
+ }
578
+ const starts = (text.match(/^# >>> (?:dsh-context-kit|dsh-preset-tuner): managed block:/gm) ?? []).length
579
+ const ends = (text.match(/^# <<< (?:dsh-context-kit|dsh-preset-tuner): managed block:/gm) ?? []).length
580
+ if (starts !== ends) problems.push(`标记不配对(begin ${starts} / end ${ends})`)
581
+ return problems
582
+ }
583
+
584
+ /** 备份 -> 写入。返回 { changed, backup, path }。 */
585
+ export function writePatchFile(profileDir, text, { keepBackups = 10 } = {}) {
586
+ const file = join(profileDir, PATCH_FILE)
587
+ const previous = existsSync(file) ? readFileSync(file, 'utf8') : ''
588
+ if (previous === text) return { changed: false, path: file, backup: null }
589
+
590
+ const eol = previous.includes('\r\n') ? '\r\n' : '\n'
591
+ const payload = eol === '\n' ? text : text.replace(/\r?\n/g, '\r\n')
592
+ let backup = null
593
+ if (previous) {
594
+ const dir = join(profileDir, 'dsh-context-kit', 'backups')
595
+ mkdirSync(dir, { recursive: true })
596
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
597
+ backup = join(dir, `${PATCH_FILE}.${stamp}.bak`)
598
+ copyFileSync(file, backup)
599
+ const old = readdirSync(dir)
600
+ .filter((name) => name.endsWith('.bak'))
601
+ .sort()
602
+ for (const name of old.slice(0, Math.max(0, old.length - keepBackups))) {
603
+ try {
604
+ unlinkSync(join(dir, name))
605
+ } catch {}
606
+ }
607
+ }
608
+ mkdirSync(profileDir, { recursive: true })
609
+ writeFileSync(file, payload, 'utf8')
610
+ return { changed: true, path: file, backup }
611
+ }
612
+
613
+ /* ─────────────────────────── profile 目录定位 ─────────────────────────── */
614
+
615
+ /**
616
+ * 定位 profile 目录。顺序:显式配置 → 环境变量 → 模块自身安装路径 →
617
+ * ~/.dsh/profiles/<配置名或 desktop> → 唯一 profile 兜底。
618
+ */
619
+ export function resolveProfileDir({ config = {}, moduleUrl, home = homedir(), env = process.env } = {}) {
620
+ if (config.profileDir) return { dir: resolve(config.profileDir), via: 'config.profileDir' }
621
+ if (env.DSH_PROFILE_DIR) return { dir: resolve(env.DSH_PROFILE_DIR), via: 'env.DSH_PROFILE_DIR' }
622
+
623
+ if (moduleUrl) {
624
+ const match = /[\\/]profiles[\\/]([^\\/]+)[\\/]/.exec(moduleUrl)
625
+ if (match) {
626
+ const base = env.DSH_HOME ? resolve(env.DSH_HOME) : join(home, '.dsh')
627
+ const candidate = join(base, 'profiles', match[1])
628
+ if (existsSync(candidate)) return { dir: candidate, via: 'module path' }
629
+ }
630
+ }
631
+
632
+ const base = env.DSH_HOME ? resolve(env.DSH_HOME) : join(home, '.dsh')
633
+ const preferred = join(base, 'profiles', config.profile ?? 'desktop')
634
+ if (existsSync(preferred)) return { dir: preferred, via: `profiles/${config.profile ?? 'desktop'}` }
635
+
636
+ const root = join(base, 'profiles')
637
+ if (existsSync(root)) {
638
+ const names = readdirSync(root, { withFileTypes: true })
639
+ .filter((entry) => entry.isDirectory() && entry.name !== 'node_modules')
640
+ .map((entry) => entry.name)
641
+ if (names.length === 1) return { dir: join(root, names[0]), via: '唯一 profile' }
642
+ if (names.length > 1) {
643
+ throw new Error(`找到多个 profile(${names.join(', ')}),请在插件配置里显式设置 profileDir`)
644
+ }
645
+ }
646
+ throw new Error('找不到 DSH profile 目录,请在插件配置里设置 profileDir')
647
+ }