dsh-context-kit 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +149 -120
- package/bin/dsh-context-kit.mjs +173 -138
- package/client/panel.js +437 -302
- package/cordis.patch.yml +21 -21
- package/icon.svg +13 -13
- package/index.js +385 -385
- package/lib/index/events.cjs +90 -90
- package/lib/index/render.cjs +177 -177
- package/lib/index/sources.cjs +286 -286
- package/lib/index/tokens.cjs +48 -48
- package/lib/kit-ops.mjs +253 -230
- package/lib/remote.mjs +59 -55
- package/lib/settings.mjs +69 -69
- package/lib/tuner/sync.mjs +140 -140
- package/lib/tuner/tuner.mjs +647 -647
- package/lib/usage.mjs +448 -0
- package/package.json +66 -65
- package/tuner.js +213 -149
- package/vendor/fzstd/LICENSE +21 -0
- package/vendor/fzstd/index.mjs +753 -0
package/lib/remote.mjs
CHANGED
|
@@ -1,55 +1,59 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Settings 面板 <-> Host 的 RPC 服务。
|
|
3
|
-
* 客户端调用:ctx.connection.rpc.call('/api', 'contextKit/<method>', { args })
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
|
7
|
-
|
|
8
|
-
/** 施加 Remote(name) 标记,兼容无装饰器的写法(与 dsh-memory-local 同款)。 */
|
|
9
|
-
export function markRemoteMethod(serviceClass, method, exportName = method) {
|
|
10
|
-
const instance = Object.create(serviceClass.prototype)
|
|
11
|
-
const decorate = Remote(exportName)
|
|
12
|
-
decorate(undefined, {
|
|
13
|
-
kind: 'method',
|
|
14
|
-
name: method,
|
|
15
|
-
static: false,
|
|
16
|
-
private: false,
|
|
17
|
-
addInitializer(fn) {
|
|
18
|
-
fn.call(instance)
|
|
19
|
-
},
|
|
20
|
-
})
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export class ContextKitRemoteService extends TypertRemoteService {
|
|
24
|
-
static inject = []
|
|
25
|
-
|
|
26
|
-
constructor(ctx, config = {}) {
|
|
27
|
-
super(ctx, 'contextKit')
|
|
28
|
-
if (!config.kit) throw new Error('contextKit remote service requires a kit')
|
|
29
|
-
this.kit = config.kit
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
status() {
|
|
33
|
-
return this.kit.describe()
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
preview() {
|
|
37
|
-
return { text: this.kit.preview() }
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
save(presetId, thresholdRatio, retainRatio, auto, group) {
|
|
41
|
-
return this.kit.saveCompaction({ presetId, thresholdRatio, retainRatio, auto, group })
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
sync(force, mode) {
|
|
45
|
-
return this.kit.sync({ force: force === true, mode: mode === 'replace' ? 'replace' : 'append' })
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
clear() {
|
|
49
|
-
return this.kit.clear()
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Settings 面板 <-> Host 的 RPC 服务。
|
|
3
|
+
* 客户端调用:ctx.connection.rpc.call('/api', 'contextKit/<method>', { args })
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
|
7
|
+
|
|
8
|
+
/** 施加 Remote(name) 标记,兼容无装饰器的写法(与 dsh-memory-local 同款)。 */
|
|
9
|
+
export function markRemoteMethod(serviceClass, method, exportName = method) {
|
|
10
|
+
const instance = Object.create(serviceClass.prototype)
|
|
11
|
+
const decorate = Remote(exportName)
|
|
12
|
+
decorate(undefined, {
|
|
13
|
+
kind: 'method',
|
|
14
|
+
name: method,
|
|
15
|
+
static: false,
|
|
16
|
+
private: false,
|
|
17
|
+
addInitializer(fn) {
|
|
18
|
+
fn.call(instance)
|
|
19
|
+
},
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class ContextKitRemoteService extends TypertRemoteService {
|
|
24
|
+
static inject = []
|
|
25
|
+
|
|
26
|
+
constructor(ctx, config = {}) {
|
|
27
|
+
super(ctx, 'contextKit')
|
|
28
|
+
if (!config.kit) throw new Error('contextKit remote service requires a kit')
|
|
29
|
+
this.kit = config.kit
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
status() {
|
|
33
|
+
return this.kit.describe()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
preview() {
|
|
37
|
+
return { text: this.kit.preview() }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
save(presetId, thresholdRatio, retainRatio, auto, group) {
|
|
41
|
+
return this.kit.saveCompaction({ presetId, thresholdRatio, retainRatio, auto, group })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
sync(force, mode) {
|
|
45
|
+
return this.kit.sync({ force: force === true, mode: mode === 'replace' ? 'replace' : 'append' })
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
clear() {
|
|
49
|
+
return this.kit.clear()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async report(days) {
|
|
53
|
+
return this.kit.report({ days: Number(days) || 7 })
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
for (const method of ['status', 'preview', 'save', 'sync', 'clear', 'report']) {
|
|
58
|
+
markRemoteMethod(ContextKitRemoteService, method)
|
|
59
|
+
}
|
package/lib/settings.mjs
CHANGED
|
@@ -1,69 +1,69 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 面板可改的少量设置,存成 JSON(不碰 profile 的 YAML)。
|
|
3
|
-
* 位置:<profile>/dsh-context-kit/settings.json
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
7
|
-
import { join } from 'node:path'
|
|
8
|
-
|
|
9
|
-
export const SETTINGS_FILE = 'settings.json'
|
|
10
|
-
export const SETTINGS_DIR = 'dsh-context-kit'
|
|
11
|
-
|
|
12
|
-
export function settingsPath(profileDir) {
|
|
13
|
-
return join(profileDir, SETTINGS_DIR, SETTINGS_FILE)
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function readSettings(profileDir) {
|
|
17
|
-
const file = settingsPath(profileDir)
|
|
18
|
-
if (!existsSync(file)) return { presets: {} }
|
|
19
|
-
try {
|
|
20
|
-
const raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
|
|
21
|
-
const parsed = JSON.parse(raw)
|
|
22
|
-
const presets = {}
|
|
23
|
-
for (const [presetId, value] of Object.entries(parsed?.presets ?? {})) {
|
|
24
|
-
if (!value || typeof value !== 'object') continue
|
|
25
|
-
presets[presetId] = {
|
|
26
|
-
plugins: value.plugins && typeof value.plugins === 'object' ? value.plugins : {},
|
|
27
|
-
add: Array.isArray(value.add) ? value.add : [],
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return { presets }
|
|
31
|
-
} catch {
|
|
32
|
-
// 坏文件当作没配置,绝不让面板/工具因此崩掉
|
|
33
|
-
return { presets: {} }
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function writeSettings(profileDir, settings) {
|
|
38
|
-
const dir = join(profileDir, SETTINGS_DIR)
|
|
39
|
-
mkdirSync(dir, { recursive: true })
|
|
40
|
-
const file = settingsPath(profileDir)
|
|
41
|
-
const payload = `${JSON.stringify({ presets: settings.presets ?? {} }, null, 2)}\n`
|
|
42
|
-
const temp = `${file}.tmp`
|
|
43
|
-
writeFileSync(temp, payload, 'utf8')
|
|
44
|
-
renameSync(temp, file)
|
|
45
|
-
return file
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** 把压缩阈值写进 presets[presetId].plugins['compaction-basic'],保留其它键。 */
|
|
49
|
-
export function setCompaction(settings, presetId, knobs, group = 'compaction') {
|
|
50
|
-
const next = {
|
|
51
|
-
presets: JSON.parse(JSON.stringify(settings.presets ?? {})),
|
|
52
|
-
}
|
|
53
|
-
const preset = next.presets[presetId] ?? { plugins: {}, add: [] }
|
|
54
|
-
const plugins = preset.plugins ?? {}
|
|
55
|
-
plugins['compaction-basic'] = {
|
|
56
|
-
...(plugins['compaction-basic'] ?? {}),
|
|
57
|
-
group: group || 'compaction',
|
|
58
|
-
config: {
|
|
59
|
-
...(plugins['compaction-basic']?.config ?? {}),
|
|
60
|
-
auto: knobs.auto !== false,
|
|
61
|
-
thresholdRatio: Number(knobs.thresholdRatio),
|
|
62
|
-
retainRatio: Number(knobs.retainRatio),
|
|
63
|
-
},
|
|
64
|
-
}
|
|
65
|
-
preset.plugins = plugins
|
|
66
|
-
preset.add = Array.isArray(preset.add) ? preset.add : []
|
|
67
|
-
next.presets[presetId] = preset
|
|
68
|
-
return next
|
|
69
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 面板可改的少量设置,存成 JSON(不碰 profile 的 YAML)。
|
|
3
|
+
* 位置:<profile>/dsh-context-kit/settings.json
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
|
|
9
|
+
export const SETTINGS_FILE = 'settings.json'
|
|
10
|
+
export const SETTINGS_DIR = 'dsh-context-kit'
|
|
11
|
+
|
|
12
|
+
export function settingsPath(profileDir) {
|
|
13
|
+
return join(profileDir, SETTINGS_DIR, SETTINGS_FILE)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function readSettings(profileDir) {
|
|
17
|
+
const file = settingsPath(profileDir)
|
|
18
|
+
if (!existsSync(file)) return { presets: {} }
|
|
19
|
+
try {
|
|
20
|
+
const raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
|
|
21
|
+
const parsed = JSON.parse(raw)
|
|
22
|
+
const presets = {}
|
|
23
|
+
for (const [presetId, value] of Object.entries(parsed?.presets ?? {})) {
|
|
24
|
+
if (!value || typeof value !== 'object') continue
|
|
25
|
+
presets[presetId] = {
|
|
26
|
+
plugins: value.plugins && typeof value.plugins === 'object' ? value.plugins : {},
|
|
27
|
+
add: Array.isArray(value.add) ? value.add : [],
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return { presets }
|
|
31
|
+
} catch {
|
|
32
|
+
// 坏文件当作没配置,绝不让面板/工具因此崩掉
|
|
33
|
+
return { presets: {} }
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function writeSettings(profileDir, settings) {
|
|
38
|
+
const dir = join(profileDir, SETTINGS_DIR)
|
|
39
|
+
mkdirSync(dir, { recursive: true })
|
|
40
|
+
const file = settingsPath(profileDir)
|
|
41
|
+
const payload = `${JSON.stringify({ presets: settings.presets ?? {} }, null, 2)}\n`
|
|
42
|
+
const temp = `${file}.tmp`
|
|
43
|
+
writeFileSync(temp, payload, 'utf8')
|
|
44
|
+
renameSync(temp, file)
|
|
45
|
+
return file
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 把压缩阈值写进 presets[presetId].plugins['compaction-basic'],保留其它键。 */
|
|
49
|
+
export function setCompaction(settings, presetId, knobs, group = 'compaction') {
|
|
50
|
+
const next = {
|
|
51
|
+
presets: JSON.parse(JSON.stringify(settings.presets ?? {})),
|
|
52
|
+
}
|
|
53
|
+
const preset = next.presets[presetId] ?? { plugins: {}, add: [] }
|
|
54
|
+
const plugins = preset.plugins ?? {}
|
|
55
|
+
plugins['compaction-basic'] = {
|
|
56
|
+
...(plugins['compaction-basic'] ?? {}),
|
|
57
|
+
group: group || 'compaction',
|
|
58
|
+
config: {
|
|
59
|
+
...(plugins['compaction-basic']?.config ?? {}),
|
|
60
|
+
auto: knobs.auto !== false,
|
|
61
|
+
thresholdRatio: Number(knobs.thresholdRatio),
|
|
62
|
+
retainRatio: Number(knobs.retainRatio),
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
preset.plugins = plugins
|
|
66
|
+
preset.add = Array.isArray(preset.add) ? preset.add : []
|
|
67
|
+
next.presets[presetId] = preset
|
|
68
|
+
return next
|
|
69
|
+
}
|
package/lib/tuner/sync.mjs
CHANGED
|
@@ -1,140 +1,140 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 把“读上游 + 生成覆盖 + 安全落盘”串成一个可复用流程。
|
|
3
|
-
* 这里不碰 ctx,只接收已解析好的路径与配置,便于单测。
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
7
|
-
import { join } from 'node:path'
|
|
8
|
-
import {
|
|
9
|
-
buildOverride,
|
|
10
|
-
checkPatchShape,
|
|
11
|
-
discoverPresets,
|
|
12
|
-
extractDeclaration,
|
|
13
|
-
findForeignRows,
|
|
14
|
-
parseManagedBlocks,
|
|
15
|
-
renderBlock,
|
|
16
|
-
resolveAppSources,
|
|
17
|
-
spliceBlocks,
|
|
18
|
-
writePatchFile,
|
|
19
|
-
PATCH_FILE,
|
|
20
|
-
} from './tuner.mjs'
|
|
21
|
-
|
|
22
|
-
const isBlank = (line) => line.trim() === ''
|
|
23
|
-
|
|
24
|
-
/** 删除顶层 `- id: preset-<id>` 行(含其后续缩进行),用于 force+replace 接管外来覆盖。 */
|
|
25
|
-
export function stripForeignRows(text, presetIds) {
|
|
26
|
-
const wanted = new Set(presetIds.map((id) => `preset-${id}`))
|
|
27
|
-
const lines = String(text ?? '').split(/\r?\n/)
|
|
28
|
-
const managed = parseManagedBlocks(text)
|
|
29
|
-
const insideManaged = new Set()
|
|
30
|
-
for (const block of managed) for (let i = block.start; i <= block.end; i += 1) insideManaged.add(i)
|
|
31
|
-
|
|
32
|
-
const drop = new Set()
|
|
33
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
34
|
-
if (insideManaged.has(i)) continue
|
|
35
|
-
const match = /^-\s+id:\s*(\S+)\s*$/.exec(lines[i])
|
|
36
|
-
if (!match || !wanted.has(match[1])) continue
|
|
37
|
-
// 该行起,到下一个顶层行/顶层注释为止。中间允许空行(preset 声明里的
|
|
38
|
-
// 块标量本身就有空行,遇到空行就停会把后半截留成孤儿续行)。
|
|
39
|
-
let lastContent = i
|
|
40
|
-
let j = i + 1
|
|
41
|
-
while (j < lines.length) {
|
|
42
|
-
if (isBlank(lines[j])) {
|
|
43
|
-
j += 1
|
|
44
|
-
continue
|
|
45
|
-
}
|
|
46
|
-
if (lines[j].startsWith('#') || lines[j].startsWith('-')) break
|
|
47
|
-
lastContent = j
|
|
48
|
-
j += 1
|
|
49
|
-
}
|
|
50
|
-
for (let k = i; k <= lastContent; k += 1) drop.add(k)
|
|
51
|
-
}
|
|
52
|
-
if (drop.size === 0) return text
|
|
53
|
-
return lines.filter((_, index) => !drop.has(index)).join('\n')
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* 只做计算不落盘:为每个配置里的预设生成覆盖块,并报告上游漂移/外来冲突。
|
|
58
|
-
* @returns {{blocks: Array, entries: Array, problems: Array<string>, missing: Array<string>}}
|
|
59
|
-
*/
|
|
60
|
-
export function planSync({ sources, presetTweaks, patchText, env = process.env, execPath = process.execPath }) {
|
|
61
|
-
const resolvedSources = sources ?? resolveAppSources({ config: { appRoot: env.DSH_APP_ROOT }, execPath })
|
|
62
|
-
const sourceErrors = []
|
|
63
|
-
const upstream = discoverPresets(resolvedSources, { onError: (message) => sourceErrors.push(message) })
|
|
64
|
-
const blocks = []
|
|
65
|
-
const entries = []
|
|
66
|
-
const problems = []
|
|
67
|
-
const missing = []
|
|
68
|
-
|
|
69
|
-
for (const [presetId, tweaks] of Object.entries(presetTweaks ?? {})) {
|
|
70
|
-
const found = upstream.get(presetId)
|
|
71
|
-
if (!found) {
|
|
72
|
-
missing.push(presetId)
|
|
73
|
-
problems.push(
|
|
74
|
-
`上游找不到预设 "${presetId}"(可能拼写有误,或该 DSH 版本没有这个预设)` +
|
|
75
|
-
(sourceErrors.length > 0 ? `;读取细节:${sourceErrors.slice(0, 3).join(' | ')}` : ''),
|
|
76
|
-
)
|
|
77
|
-
continue
|
|
78
|
-
}
|
|
79
|
-
try {
|
|
80
|
-
const declaration = extractDeclaration(found.text, presetId)
|
|
81
|
-
const lines = buildOverride(declaration.lines, tweaks)
|
|
82
|
-
const rendered = renderBlock({
|
|
83
|
-
presetId,
|
|
84
|
-
upstreamSha: found.sha,
|
|
85
|
-
upstreamPath: found.internalPath,
|
|
86
|
-
declarationLines: lines,
|
|
87
|
-
})
|
|
88
|
-
blocks.push(rendered)
|
|
89
|
-
const existingBlock = parseManagedBlocks(patchText).find((block) => block.presetId === presetId)
|
|
90
|
-
entries.push({
|
|
91
|
-
presetId,
|
|
92
|
-
upstreamSha: found.sha,
|
|
93
|
-
previousSha: existingBlock?.sha,
|
|
94
|
-
drifted: Boolean(existingBlock && existingBlock.sha && existingBlock.sha !== found.sha),
|
|
95
|
-
pluginCount: (found.text.match(/^\s+-\s+id:/gm) ?? []).length,
|
|
96
|
-
upstreamPath: found.internalPath,
|
|
97
|
-
})
|
|
98
|
-
} catch (error) {
|
|
99
|
-
problems.push(`${presetId}: ${error.message}`)
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
return { blocks, entries, problems, missing, upstream }
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* 落盘。任何校验不通过都不写文件(失败即放弃,宁可没效果也不弄坏启动)。
|
|
108
|
-
* @returns {{changed: boolean, path: string, backup: string|null, removedForeign: number}}
|
|
109
|
-
*/
|
|
110
|
-
export function commitSync({ profileDir, blocks, presetIds, patchText, force = false, mode = 'append' }) {
|
|
111
|
-
const file = join(profileDir, PATCH_FILE)
|
|
112
|
-
let text = patchText
|
|
113
|
-
if (text === undefined) text = existsSync(file) ? readFileSync(file, 'utf8') : ''
|
|
114
|
-
|
|
115
|
-
const foreign = presetIds.flatMap((id) => findForeignRows(text, id))
|
|
116
|
-
if (foreign.length > 0 && !force) {
|
|
117
|
-
throw new Error(
|
|
118
|
-
`${PATCH_FILE} 里已有手写的 preset 覆盖(第 ${foreign.map((n) => n + 1).join(', ')} 行),` +
|
|
119
|
-
'为避免吞掉你的内容,本次没有写入。先手工删除那几行,或传 force 并选择 mode="replace" 由插件接管。',
|
|
120
|
-
)
|
|
121
|
-
}
|
|
122
|
-
if (foreign.length > 0 && force && mode !== 'replace') {
|
|
123
|
-
throw new Error('force 只配合 mode="replace" 使用:否则会留下两条同 id 的覆盖行')
|
|
124
|
-
}
|
|
125
|
-
let removedForeign = 0
|
|
126
|
-
if (foreign.length > 0 && force) {
|
|
127
|
-
removedForeign = foreign.length
|
|
128
|
-
text = stripForeignRows(text, presetIds)
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
const next = spliceBlocks(text, blocks)
|
|
132
|
-
const shapeProblems = checkPatchShape(next)
|
|
133
|
-
if (shapeProblems.length > 0) {
|
|
134
|
-
throw new Error(`生成的补丁没有通过结构校验,已放弃写入:${shapeProblems.join('; ')}`)
|
|
135
|
-
}
|
|
136
|
-
const result = writePatchFile(profileDir, next)
|
|
137
|
-
return { ...result, removedForeign }
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export { PATCH_FILE }
|
|
1
|
+
/**
|
|
2
|
+
* 把“读上游 + 生成覆盖 + 安全落盘”串成一个可复用流程。
|
|
3
|
+
* 这里不碰 ctx,只接收已解析好的路径与配置,便于单测。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import {
|
|
9
|
+
buildOverride,
|
|
10
|
+
checkPatchShape,
|
|
11
|
+
discoverPresets,
|
|
12
|
+
extractDeclaration,
|
|
13
|
+
findForeignRows,
|
|
14
|
+
parseManagedBlocks,
|
|
15
|
+
renderBlock,
|
|
16
|
+
resolveAppSources,
|
|
17
|
+
spliceBlocks,
|
|
18
|
+
writePatchFile,
|
|
19
|
+
PATCH_FILE,
|
|
20
|
+
} from './tuner.mjs'
|
|
21
|
+
|
|
22
|
+
const isBlank = (line) => line.trim() === ''
|
|
23
|
+
|
|
24
|
+
/** 删除顶层 `- id: preset-<id>` 行(含其后续缩进行),用于 force+replace 接管外来覆盖。 */
|
|
25
|
+
export function stripForeignRows(text, presetIds) {
|
|
26
|
+
const wanted = new Set(presetIds.map((id) => `preset-${id}`))
|
|
27
|
+
const lines = String(text ?? '').split(/\r?\n/)
|
|
28
|
+
const managed = parseManagedBlocks(text)
|
|
29
|
+
const insideManaged = new Set()
|
|
30
|
+
for (const block of managed) for (let i = block.start; i <= block.end; i += 1) insideManaged.add(i)
|
|
31
|
+
|
|
32
|
+
const drop = new Set()
|
|
33
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
34
|
+
if (insideManaged.has(i)) continue
|
|
35
|
+
const match = /^-\s+id:\s*(\S+)\s*$/.exec(lines[i])
|
|
36
|
+
if (!match || !wanted.has(match[1])) continue
|
|
37
|
+
// 该行起,到下一个顶层行/顶层注释为止。中间允许空行(preset 声明里的
|
|
38
|
+
// 块标量本身就有空行,遇到空行就停会把后半截留成孤儿续行)。
|
|
39
|
+
let lastContent = i
|
|
40
|
+
let j = i + 1
|
|
41
|
+
while (j < lines.length) {
|
|
42
|
+
if (isBlank(lines[j])) {
|
|
43
|
+
j += 1
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
if (lines[j].startsWith('#') || lines[j].startsWith('-')) break
|
|
47
|
+
lastContent = j
|
|
48
|
+
j += 1
|
|
49
|
+
}
|
|
50
|
+
for (let k = i; k <= lastContent; k += 1) drop.add(k)
|
|
51
|
+
}
|
|
52
|
+
if (drop.size === 0) return text
|
|
53
|
+
return lines.filter((_, index) => !drop.has(index)).join('\n')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 只做计算不落盘:为每个配置里的预设生成覆盖块,并报告上游漂移/外来冲突。
|
|
58
|
+
* @returns {{blocks: Array, entries: Array, problems: Array<string>, missing: Array<string>}}
|
|
59
|
+
*/
|
|
60
|
+
export function planSync({ sources, presetTweaks, patchText, env = process.env, execPath = process.execPath }) {
|
|
61
|
+
const resolvedSources = sources ?? resolveAppSources({ config: { appRoot: env.DSH_APP_ROOT }, execPath })
|
|
62
|
+
const sourceErrors = []
|
|
63
|
+
const upstream = discoverPresets(resolvedSources, { onError: (message) => sourceErrors.push(message) })
|
|
64
|
+
const blocks = []
|
|
65
|
+
const entries = []
|
|
66
|
+
const problems = []
|
|
67
|
+
const missing = []
|
|
68
|
+
|
|
69
|
+
for (const [presetId, tweaks] of Object.entries(presetTweaks ?? {})) {
|
|
70
|
+
const found = upstream.get(presetId)
|
|
71
|
+
if (!found) {
|
|
72
|
+
missing.push(presetId)
|
|
73
|
+
problems.push(
|
|
74
|
+
`上游找不到预设 "${presetId}"(可能拼写有误,或该 DSH 版本没有这个预设)` +
|
|
75
|
+
(sourceErrors.length > 0 ? `;读取细节:${sourceErrors.slice(0, 3).join(' | ')}` : ''),
|
|
76
|
+
)
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const declaration = extractDeclaration(found.text, presetId)
|
|
81
|
+
const lines = buildOverride(declaration.lines, tweaks)
|
|
82
|
+
const rendered = renderBlock({
|
|
83
|
+
presetId,
|
|
84
|
+
upstreamSha: found.sha,
|
|
85
|
+
upstreamPath: found.internalPath,
|
|
86
|
+
declarationLines: lines,
|
|
87
|
+
})
|
|
88
|
+
blocks.push(rendered)
|
|
89
|
+
const existingBlock = parseManagedBlocks(patchText).find((block) => block.presetId === presetId)
|
|
90
|
+
entries.push({
|
|
91
|
+
presetId,
|
|
92
|
+
upstreamSha: found.sha,
|
|
93
|
+
previousSha: existingBlock?.sha,
|
|
94
|
+
drifted: Boolean(existingBlock && existingBlock.sha && existingBlock.sha !== found.sha),
|
|
95
|
+
pluginCount: (found.text.match(/^\s+-\s+id:/gm) ?? []).length,
|
|
96
|
+
upstreamPath: found.internalPath,
|
|
97
|
+
})
|
|
98
|
+
} catch (error) {
|
|
99
|
+
problems.push(`${presetId}: ${error.message}`)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return { blocks, entries, problems, missing, upstream }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 落盘。任何校验不通过都不写文件(失败即放弃,宁可没效果也不弄坏启动)。
|
|
108
|
+
* @returns {{changed: boolean, path: string, backup: string|null, removedForeign: number}}
|
|
109
|
+
*/
|
|
110
|
+
export function commitSync({ profileDir, blocks, presetIds, patchText, force = false, mode = 'append' }) {
|
|
111
|
+
const file = join(profileDir, PATCH_FILE)
|
|
112
|
+
let text = patchText
|
|
113
|
+
if (text === undefined) text = existsSync(file) ? readFileSync(file, 'utf8') : ''
|
|
114
|
+
|
|
115
|
+
const foreign = presetIds.flatMap((id) => findForeignRows(text, id))
|
|
116
|
+
if (foreign.length > 0 && !force) {
|
|
117
|
+
throw new Error(
|
|
118
|
+
`${PATCH_FILE} 里已有手写的 preset 覆盖(第 ${foreign.map((n) => n + 1).join(', ')} 行),` +
|
|
119
|
+
'为避免吞掉你的内容,本次没有写入。先手工删除那几行,或传 force 并选择 mode="replace" 由插件接管。',
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
if (foreign.length > 0 && force && mode !== 'replace') {
|
|
123
|
+
throw new Error('force 只配合 mode="replace" 使用:否则会留下两条同 id 的覆盖行')
|
|
124
|
+
}
|
|
125
|
+
let removedForeign = 0
|
|
126
|
+
if (foreign.length > 0 && force) {
|
|
127
|
+
removedForeign = foreign.length
|
|
128
|
+
text = stripForeignRows(text, presetIds)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const next = spliceBlocks(text, blocks)
|
|
132
|
+
const shapeProblems = checkPatchShape(next)
|
|
133
|
+
if (shapeProblems.length > 0) {
|
|
134
|
+
throw new Error(`生成的补丁没有通过结构校验,已放弃写入:${shapeProblems.join('; ')}`)
|
|
135
|
+
}
|
|
136
|
+
const result = writePatchFile(profileDir, next)
|
|
137
|
+
return { ...result, removedForeign }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export { PATCH_FILE }
|