dsh-cookie-cleaner 0.1.2 → 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.
@@ -0,0 +1,312 @@
1
+ /**
2
+ * dsh-cookie-cleaner — patch 结构判定内核(纯函数,零 IO)。
3
+ *
4
+ * 存在的理由:profile 的 `cordis.patch.yml` 是**补丁层**而不是条目列表,它的语义有三个
5
+ * 反直觉的坑(全部有源码依据,见 `.agents/plans/cookie-patch-guard/findings.md`):
6
+ *
7
+ * 1. patch 行按**顶层键浅赋值**(`cordis-plugin-include/src/index.ts:120-123`),所以
8
+ * `config:` 是整块替换而非深合并——漏写的键落回该插件的 **schema 默认**,不是落回
9
+ * bundle 层的值(`webserver.compression` 默认就是 `none`);
10
+ * 2. `name` 与宿主 bundle 行不一致时**整行静默跳过**,只在启动日志留一行 warn;
11
+ * 3. 层顺序是 bundle layers → profile → **home** → `--patch` overlay,home 里同 id 行会把
12
+ * profile 的写盖掉(官方 `configEditor` 写前检查的正是这一条)。
13
+ *
14
+ * 本模块只吃数据、只出结构化判定(code/level/params),**不碰文件系统、不取宿主服务、
15
+ * 不出文案**:文案由 `report.js` 经 i18n 字典渲染,IO 由 `patch-guard.js`(宿主半)与
16
+ * `cli.js`(只读行解析)各自负责。这样宿主半与 CLI 共用一份判定,不可能各说一套。
17
+ */
18
+
19
+ /** @typedef {'ok'|'warn'|'fail'|'skipped'} Level */
20
+
21
+ /** 受管行:`writable` = 「修复」按钮可动(只给 cookie 寿命);端口走另一个显式动作(PORT_WRITE)。 */
22
+ export const MANAGED_ROWS = Object.freeze({
23
+ connection: Object.freeze({
24
+ id: 'connection',
25
+ name: '@deepseek-ai/dsh-client-connection',
26
+ writable: true,
27
+ /** cookie 寿命的唯一杠杆(`connection/src/index.ts:113` 为 `natural().min(1).default(30)`)。 */
28
+ key: 'cookieMaxAgeDays',
29
+ minimum: 1,
30
+ }),
31
+ webserver: Object.freeze({
32
+ id: 'webserver',
33
+ name: '@deepseek-ai/dsh-host-webserver',
34
+ writable: false,
35
+ key: 'port',
36
+ }),
37
+ })
38
+
39
+ /**
40
+ * 端口写入门面(面板的「应用端口」专用,不并进「修复」)。
41
+ * 本仓代码**不携带任何具体端口常量**:目标值只能来自用户输入,回落值只从宿主/用户已有的
42
+ * 表达式里拿(见 portExpressionFor)。
43
+ */
44
+ export const PORT_WRITE = Object.freeze({
45
+ rowId: 'webserver',
46
+ key: 'port',
47
+ minimum: 1,
48
+ maximum: 65535,
49
+ })
50
+
51
+ export function isValidPort(value) {
52
+ return Number.isInteger(value) && value >= PORT_WRITE.minimum && value <= PORT_WRITE.maximum
53
+ }
54
+
55
+ /** 档位优先级:聚合时取最高;`skipped` 中性,永不冒充异常。 */
56
+ const LEVEL_RANK = Object.freeze({ fail: 3, warn: 2, ok: 1, skipped: 0 })
57
+
58
+ /** `!!js` 表达式在 configEditor 往返里的表示形态(VERIFIED@0.2.1-rc.5)。 */
59
+ export function isExpression(value) {
60
+ return value !== null && typeof value === 'object' && typeof value.__jsExpr === 'string' && Object.keys(value).length === 1
61
+ }
62
+
63
+ function nonNegativeInt(value) {
64
+ return typeof value === 'number' && Number.isInteger(value)
65
+ }
66
+
67
+ /** 结构比较(值都是 JSON 安全形态:标量/数组/对象/`{__jsExpr}`)。 */
68
+ function sameValue(a, b) {
69
+ if (a === b) return true
70
+ try { return JSON.stringify(a) === JSON.stringify(b) } catch { return false }
71
+ }
72
+
73
+ /**
74
+ * 值是否“有料”:空对象/空数组/空串/false/0 都视为默认形态(拿不出行为差异)。
75
+ * 真机教训:`webserver.tls` 在 bundle 层与运行态之间只是 `{}` 与缺省形态的区别,
76
+ * 却被告知「有偏差」——两边都空就没什么可报的。
77
+ */
78
+ function isMaterial(value) {
79
+ if (value === null || value === undefined) return false
80
+ if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') return value !== false && value !== 0 && value !== ''
81
+ if (Array.isArray(value)) return value.length > 0 && value.some(isMaterial)
82
+ if (typeof value === 'object') return Object.values(value).some(isMaterial)
83
+ return true
84
+ }
85
+
86
+ /**
87
+ * 非表达式键:只有「运行态与 bundle 层不同值、且至少一边真有内容」才算**可证明的丢**。
88
+ * 真机噪声源:`webserver.tls` 这类 schema 默认键——浅赋值下它没写进覆盖行,
89
+ * 但两边都只有默认形态(`{}` vs 缺省),行为上什么都没变,却被报成「有偏差」。
90
+ * 运行态根本没有这个键 → 无从判定,中性,不编造结论。
91
+ */
92
+ function isProvenLoss(key, inheritedValue, effective) {
93
+ if (!(key in effective)) return false
94
+ if (sameValue(inheritedValue, effective[key])) return false
95
+ return isMaterial(inheritedValue) || isMaterial(effective[key])
96
+ }
97
+
98
+ /**
99
+ * 判定单行。参数全部是**已经读好的数据**:
100
+ * @param {{
101
+ * rowId: 'connection'|'webserver',
102
+ * entryFound: boolean, // 宿主树里是否存在该 id 的可寻址条目
103
+ * overrideRow?: {name?:string, config?:Record<string,unknown>}, // profile 层的那一行
104
+ * inherited?: Record<string, unknown>, // bundle 层配置(可能含 {__jsExpr})
105
+ * effective?: Record<string, unknown>, // 运行时组合后的配置
106
+ * targetDays?: number, // connection 的目标寿命;webserver 忽略
107
+ * shadowedBy?: 'home'|'overlay'|null,
108
+ * fileParse?: {ok: boolean, reason?: string},
109
+ * }} input
110
+ * @returns {{rowId:string, writable:boolean, level:Level, findings:Array<{code:string, level:Level, params:object}>}}
111
+ */
112
+ export function assessRow(input) {
113
+ const spec = MANAGED_ROWS[input.rowId]
114
+ const findings = []
115
+ const push = (code, level, params = {}) => findings.push({ code, level, params })
116
+ const out = { rowId: input.rowId, writable: spec !== undefined && spec.writable === true, level: 'ok', findings, exprFrozen: [] }
117
+
118
+ if (spec === undefined) {
119
+ push('P00', 'skipped', { rowId: String(input.rowId) })
120
+ return aggregate(out)
121
+ }
122
+
123
+ // P11:整层 YAML 非法(典型成因是模板根 `[]` 后面又追了分块行)——所有覆盖一起失效
124
+ if (input.fileParse !== undefined && input.fileParse.ok === false) {
125
+ push('P11', 'fail', { reason: input.fileParse.reason ?? 'invalid yaml' })
126
+ return aggregate(out)
127
+ }
128
+
129
+ const { overrideRow, inherited = {}, effective = {} } = input
130
+ const shadow = input.shadowedBy ?? null
131
+
132
+ // P6:home 层或命令行 overlay 含同 id 行 → profile 的写会被盖掉(configEditor 也会拒写)
133
+ if (shadow !== null) {
134
+ push('P6', 'fail', { shadow, rowId: spec.id })
135
+ }
136
+
137
+ // P10:该 id 在当前宿主树里不存在 → 裸覆盖行静默跳过(`patch: entry "x" not found`)
138
+ if (input.entryFound === false) {
139
+ push('P10', 'fail', { rowId: spec.id, name: String(overrideRow?.name ?? spec.name) })
140
+ return aggregate(out)
141
+ }
142
+
143
+ if (overrideRow === undefined) {
144
+ // P1:没有覆盖行,且运行值确实不在目标档
145
+ if (spec.id === 'connection') {
146
+ const live = effective[spec.key]
147
+ if (live !== input.targetDays) push('P1', 'warn', { current: live ?? '默认 30', target: input.targetDays })
148
+ }
149
+ return aggregate(out)
150
+ }
151
+
152
+ // P2:name 不一致 → 整行被静默跳过,配置实际未生效(最阴的一类:用户以为配上了)
153
+ if (overrideRow.name !== undefined && overrideRow.name !== spec.name) {
154
+ push('P2', 'fail', { got: String(overrideRow.name), expected: spec.name })
155
+ return aggregate(out)
156
+ }
157
+
158
+ const config = overrideRow.config ?? {}
159
+
160
+ if (spec.id === 'connection') {
161
+ const value = config[spec.key]
162
+ // P4:非法值(<1 / 非整数)。schema 会在落盘前挡住,所以这里是「别去试写」的硬闸
163
+ if (value !== undefined && (!nonNegativeInt(value) || value < spec.minimum)) {
164
+ push('P4', 'fail', { key: spec.key, got: String(value), minimum: spec.minimum })
165
+ }
166
+ // P3:合法但偏档
167
+ else if (typeof value === 'number' && input.targetDays !== undefined && value > input.targetDays) {
168
+ push('P3', 'warn', { key: spec.key, current: value, target: input.targetDays })
169
+ }
170
+ }
171
+
172
+ // P5:只报**可证明的丢**(运行态与 bundle 层不同值且至少一边有内容)。键名清单不是证据。
173
+ const dropped = Object.keys(inherited).filter((key) => !(key in config))
174
+ const lostExpr = dropped.filter((key) => isExpression(inherited[key]))
175
+ const provenLost = dropped.filter((key) => !isExpression(inherited[key]) && isProvenLoss(key, inherited[key], effective))
176
+ if (provenLost.length > 0) {
177
+ push('P5', 'warn', { rowId: spec.id, dropped: provenLost })
178
+ }
179
+
180
+ // P7:文件里的值与运行时组合值不一致 → 上层覆盖或热应用未跟上
181
+ if (spec.id === 'connection' && config[spec.key] !== undefined && effective[spec.key] !== undefined
182
+ && config[spec.key] !== effective[spec.key] && shadow === null) {
183
+ push('P7', 'fail', { file: config[spec.key], effective: effective[spec.key] })
184
+ }
185
+
186
+ if (spec.id === 'webserver') {
187
+ // P8:port 写成字面量会夺走 `--port` 旗标权(cmdline 文档原话「a flag beats the value written beside it」)
188
+ const port = config[spec.key]
189
+ if (port !== undefined && !isExpression(port)) {
190
+ push('P8', 'warn', { port })
191
+ }
192
+ }
193
+
194
+ // P9(表达式没保住形态)**不再进体检结论**:我们无权求值那个表达式,拿不出“现状有变化”的证据。
195
+ // 两种形态都在这里:`frozen`(覆盖层抄成了字面量)与 `lostExpr`(根本没写,表达式整块被打掉)。
196
+ // 数据留在 row.exprFrozen,由 plan/粘贴块那里说(那里同时能给回跟随形态的写法)。
197
+ const frozen = Object.keys(inherited).filter((key) => isExpression(inherited[key]) && key in config && !isExpression(config[key]))
198
+ const exprGone = [...frozen, ...lostExpr].sort()
199
+ if (exprGone.length > 0) out.exprFrozen = exprGone
200
+
201
+ return aggregate(out)
202
+ }
203
+
204
+ /** 聚合档位(fail > warn > ok;全为 skipped 才是 skipped,中性结论不得被当成 ok 或异常)。 */
205
+ export function aggregate(result) {
206
+ const meaningful = result.findings.filter((f) => f.level !== 'skipped')
207
+ if (result.findings.length === 0) result.level = 'ok'
208
+ else if (meaningful.length === 0) result.level = 'skipped'
209
+ else {
210
+ const levels = meaningful.map((f) => f.level)
211
+ result.level = levels.reduce((acc, level) => (LEVEL_RANK[level] > LEVEL_RANK[acc] ? level : acc), levels[0])
212
+ }
213
+ // 可动作 = writable 且有非中性结论,且没有「写了也没用」的硬因:
214
+ // P2 name 不对(要改的是文件里的字)、P4 非法值(schema 会拒)、P6 上层影子(盖不住)、
215
+ // P10 id 不存在(写了也白写)、P11 整层非法(先修 YAML)。
216
+ const blocked = ['P2', 'P4', 'P6', 'P10', 'P11']
217
+ result.blocked = meaningful.some((f) => blocked.includes(f.code))
218
+ result.actionable = result.writable === true
219
+ && (result.level === 'warn' || result.level === 'fail')
220
+ && !result.blocked
221
+ return result
222
+ }
223
+
224
+ /** 整体聚合:任一 fail 即 fail;全 ok 才 ok。 */
225
+ export function aggregateAll(rows) {
226
+ const usable = rows.filter((row) => row.level !== 'skipped')
227
+ if (usable.length === 0) return { level: 'skipped', rows }
228
+ const level = usable.some((row) => row.level === 'fail') ? 'fail' : usable.some((row) => row.level === 'warn') ? 'warn' : 'ok'
229
+ return { level, rows }
230
+ }
231
+
232
+ /**
233
+ * 端口表达式的写法:**绝不写裸字面量**(那会夺走 `--port` 旗标权),统一用
234
+ * `ctx.webStartup.port ?? +<数字>`:`??` 只在启动层未传端口时兜底,`+` 把回落值显式转成数字
235
+ * (防运行期 `webStartup.port` 以字符串形态进来时 `z.natural()` 报 expected number)。范围校验在代码里做。
236
+ * 优先复用已有表达式只换末尾数字(保留宿主写法);本仓不假设默认端口是哪个数。
237
+ */
238
+ export function portExpressionFor(existing, port) {
239
+ const expr = isExpression(existing) ? String(existing.__jsExpr) : ''
240
+ const withPort = expr.replace(/\+?\d+\s*$/, `+${String(port)}`)
241
+ // 末尾有数字且不是目标值 → 只换它
242
+ if (withPort !== expr) return withPort
243
+ // 尾数已经是目标值 → 原样返回(幂等:不得把自己模板化)
244
+ if (/\+?\d+\s*$/.test(expr)) return expr
245
+ // 没有可复用的表达式 → 用规范形式
246
+ return `ctx.webStartup.port ?? +${String(port)}`
247
+ }
248
+
249
+ /**
250
+ * 端口写入意图:只动 `port` 一键(其余键按运行态原样保留,表达式形态也原样保留)。
251
+ * @param {{current:Record<string,unknown>, inherited?:Record<string,unknown>, port:number}} input
252
+ */
253
+ export function nextPortConfig(input) {
254
+ const current = input.current ?? {}
255
+ const target = input.port
256
+ if (!isValidPort(target)) return { next: current, changed: [], invalid: true }
257
+ const expr = portExpressionFor(isExpression(current[PORT_WRITE.key]) ? current[PORT_WRITE.key] : input.inherited?.[PORT_WRITE.key], target)
258
+ const next = { ...current, [PORT_WRITE.key]: { __jsExpr: expr } }
259
+ const already = isExpression(current[PORT_WRITE.key]) && current[PORT_WRITE.key].__jsExpr === expr
260
+ return { next, changed: already ? [] : [PORT_WRITE.key], expr }
261
+ }
262
+
263
+ /**
264
+ * 产出写意图。**关键性质(VERIFIED@0.2.1-rc.5)**:`current` 来自运行时组合配置,
265
+ * 其中表达式键已是 `{__jsExpr}` 形态,所以展开即保留——用户改过的 port、既有的表达式
266
+ * 都不会被刷掉;我们只动要求的那一键。
267
+ * @param {{current:Record<string,unknown>, targetDays?:number, guardMode?:'literal'|'expression', inherited?:Record<string,unknown>}} input
268
+ * @returns {{next:Record<string,unknown>, changed:string[]}}
269
+ */
270
+ export function nextConfigFor(input) {
271
+ const current = input.current ?? {}
272
+ const next = { ...current }
273
+ const changed = []
274
+
275
+ if (input.targetDays !== undefined && next.cookieMaxAgeDays !== input.targetDays) {
276
+ next.cookieMaxAgeDays = input.targetDays
277
+ changed.push('cookieMaxAgeDays')
278
+ }
279
+ // 表达式档:把 bundle 层本来就是表达式的键还原成 `{__jsExpr}`(表达式串取自 inherited,绝不硬编码)
280
+ if (input.guardMode === 'expression' && input.inherited !== undefined) {
281
+ for (const [key, value] of Object.entries(input.inherited)) {
282
+ if (isExpression(value) && !isExpression(next[key])) {
283
+ next[key] = value
284
+ changed.push(key)
285
+ }
286
+ }
287
+ }
288
+ return { next, changed }
289
+ }
290
+
291
+ /**
292
+ * 生成可直接粘贴的 patch 块(用于只读面:webserver 行、以及 CLI 无法写时的处方)。
293
+ * 输出块序列形态,并提示 flow `[]` 根的坑(P11)。
294
+ * @param {{rowId:'connection'|'webserver', inherited:Record<string,unknown>, current?:Record<string,unknown>, targetDays?:number, guardMode?:'literal'|'expression'}} input
295
+ */
296
+ export function renderPlanBlock(input) {
297
+ const spec = MANAGED_ROWS[input.rowId]
298
+ const source = { ...(input.inherited ?? {}), ...(input.current ?? {}) }
299
+ // 目标值在合成时就写进表里,避开「生成后再正则回改」这条脆路
300
+ if (spec.id === 'connection' && input.targetDays !== undefined) source[spec.key] = input.targetDays
301
+ const lines = [`- id: ${spec.id}`, ` name: '${spec.name}'`, ' config:']
302
+ for (const [key, value] of Object.entries(source)) {
303
+ if (isExpression(value)) {
304
+ lines.push(` ${key}: !!js ${value.__jsExpr}`)
305
+ }
306
+ else if (value === undefined) continue
307
+ else if (Array.isArray(value)) lines.push(` ${key}: ${value.length === 0 ? '[]' : JSON.stringify(value)}`)
308
+ else if (typeof value === 'string') lines.push(` ${key}: '${value}'`)
309
+ else lines.push(` ${key}: ${value}`)
310
+ }
311
+ return lines.join('\n')
312
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * dsh-cookie-cleaner — profile patch 的**只读**解析器。
3
+ *
4
+ * 为什么手写而不引 YAML 库:插件要能在客户端关闭、宿主不存在的时候裸跑(npm bin),
5
+ * 引第三方 YAML 会把「多一个依赖就多一次装机风险」搬进一个清理工具。
6
+ * 代价被诚实地框住:这里只认 profile patch 层的**实际语法子集**——
7
+ * 顶层块序列 `- ` 在第 0 列;`- id:` 覆盖行 / `- insert:` 新增行;
8
+ * 条目字段 `id|name|config` 缩进 2;config 键缩进 4(靠「比 config: 更深」判定);
9
+ * 值形态只认 数字 / 布尔 / `'quoted'` / `[a, b]` / `[]` / `!!js 表达式`;行尾 ` #` 注释可剥。
10
+ * 遇到子集外的构造(多文档、锚点、行内 flow 映射、游离缩进)一律 `ok:false` + 原因,
11
+ * 由内核报 P11/skipped——**猜错的判定比不判定更坏**。
12
+ *
13
+ * 本模块只做数据,不判档、不写盘。
14
+ */
15
+ import fs from 'node:fs'
16
+
17
+ /** 行的字段/值识别(行首 `- ` 与深度都直接在本层处理,不另存正则)。 */
18
+ const KEY_VALUE = /^(\w+):\s*(.*)$/
19
+
20
+ /** 解析一个 YAML 标量(够用子集)。`!!js` 前缀转成内核认识的 {__jsExpr}。 */
21
+ function parseScalar(raw) {
22
+ const text = String(raw ?? '').trim()
23
+ if (text === '' || text === '~' || text === 'null') return undefined
24
+ if (text.startsWith('!!js ')) return { __jsExpr: text.slice(5).trim() }
25
+ if (text === '[]') return []
26
+ if (text.startsWith('[') && text.endsWith(']')) {
27
+ const inner = text.slice(1, -1).trim()
28
+ if (inner === '') return []
29
+ return inner.split(',').map((part) => stripQuotes(part.trim()))
30
+ }
31
+ if (/^[-+]?\d+$/.test(text)) return Number(text)
32
+ if (/^[-+]?\d*\.\d+$/.test(text)) return Number(text)
33
+ if (text === 'true' || text === 'false') return text === 'true'
34
+ return stripQuotes(text)
35
+ }
36
+
37
+ function stripQuotes(text) {
38
+ if (text.length >= 2 && ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"')))) {
39
+ return text.slice(1, -1)
40
+ }
41
+ return text
42
+ }
43
+
44
+ /** 剥行尾注释(` #` 才算,行首 `#` 是整行注释,交给调用方跳过)。 */
45
+ function stripComment(line) {
46
+ const idx = line.indexOf(' #')
47
+ return idx === -1 ? line : line.slice(0, idx)
48
+ }
49
+
50
+ function indentOf(line) {
51
+ return line.match(/^\s*/)[0].length
52
+ }
53
+
54
+ function applyField(entry, key, raw) {
55
+ if (key === 'id') entry.id = String(parseScalar(raw) ?? '')
56
+ else if (key === 'name') entry.name = parseScalar(raw)
57
+ else if (key === 'config') entry.config = entry.config ?? {}
58
+ else entry[key] = parseScalar(raw)
59
+ }
60
+
61
+ /**
62
+ * 解析 patch 文本。
63
+ *
64
+ * 只读**本层需要看到的深度**:顶层行(indent 0)与它的 `id|name|config`(indent 2)、
65
+ * config 键(indent 4);insert 块的新增条目(indent 4 及其字段 indent 6)。
66
+ * **更深的嵌套(如 `providers:` 里的模型列表)直接跳过而不是判错**——真实 profile
67
+ * 大量存在这种结构,把它们当语法错误会误报“整层失效”(真机踩到)。
68
+ * @param {string} text
69
+ * @returns {{ok: boolean, reason?: string, rows: Array<object>, hadFlowRoot: boolean, skippedDeep: number}}
70
+ */
71
+ export function parsePatchText(text) {
72
+ const rows = []
73
+ let current = null // 当前顶层行
74
+ let entry = null // 当前正在填字段的条目(顶层行本身,或 insert 的子条目)
75
+ let fieldsIndent = 2 // 当前条目字段的缩进(顶层行 2;insert 子条目 6)
76
+ let inConfig = false
77
+ let configIndent = -1
78
+ let hadFlowRoot = false
79
+ let blockAfterFlowRoot = false
80
+ let skippedDeep = 0
81
+ const fail = (reason) => ({ ok: false, reason, rows, hadFlowRoot, skippedDeep })
82
+
83
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
84
+ const line = stripComment(rawLine)
85
+ if (line.trim() === '' || /^\s*#/.test(line)) continue
86
+ if (/^\[\]\s*$/.test(line)) { hadFlowRoot = true; continue }
87
+ if (/^---/.test(line) || /^[^#]*&\w+/.test(line)) return fail('unsupported yaml construct')
88
+
89
+ const indent = indentOf(line)
90
+ const item = /^\s*-\s+(.*)$/.exec(line)
91
+
92
+ if (item !== null && indent === 0) {
93
+ if (hadFlowRoot) blockAfterFlowRoot = true
94
+ inConfig = false
95
+ configIndent = -1
96
+ fieldsIndent = 2
97
+ const content = item[1].trim()
98
+ current = { insert: /^insert:\s*$/.test(content), bareId: !/^id:/.test(content) }
99
+ rows.push(current)
100
+ entry = current
101
+ if (current.insert) continue
102
+ const kv = content.match(KEY_VALUE)
103
+ if (kv === null) return fail(`unparsable row header: ${content.slice(0, 40)}`)
104
+ if (kv[1] === 'config') {
105
+ if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
106
+ configIndent = fieldsIndent
107
+ inConfig = true
108
+ applyField(entry, 'config', kv[2])
109
+ }
110
+ else applyField(entry, kv[1], kv[2])
111
+ continue
112
+ }
113
+
114
+ if (item !== null && indent > 0) {
115
+ // insert 块的新增条目(indent 4);再深就是 config 里的嵌套列表 → 跳过不判
116
+ if (current !== null && current.insert === true && indent === 4) {
117
+ inConfig = false
118
+ configIndent = -1
119
+ fieldsIndent = indent + 2
120
+ entry = { insert: false, bareId: false }
121
+ current.entries = current.entries ?? []
122
+ current.entries.push(entry)
123
+ const kv = item[1].trim().match(KEY_VALUE)
124
+ if (kv !== null) applyField(entry, kv[1], kv[2])
125
+ continue
126
+ }
127
+ skippedDeep += 1
128
+ continue
129
+ }
130
+
131
+ const kv = line.trim().match(KEY_VALUE)
132
+ if (kv === null) { skippedDeep += 1; continue }
133
+ if (entry === null) return fail('unexpected top-level indentation')
134
+
135
+ // config 的键:深度必须恰好比 `config:` 本身多 2;更深的值是嵌套结构,不属于本次判定
136
+ if (inConfig && indent === configIndent + 2) {
137
+ if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
138
+ entry.config = entry.config ?? {}
139
+ entry.config[kv[1]] = parseScalar(kv[2])
140
+ continue
141
+ }
142
+ if (inConfig && indent > configIndent + 2) { skippedDeep += 1; continue }
143
+ inConfig = false
144
+ if (indent !== fieldsIndent) { skippedDeep += 1; continue }
145
+ if (kv[1] === 'config') {
146
+ if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
147
+ configIndent = indent
148
+ inConfig = kv[2].trim() === ''
149
+ applyField(entry, 'config', kv[2])
150
+ continue
151
+ }
152
+ applyField(entry, kv[1], kv[2])
153
+ }
154
+
155
+ if (hadFlowRoot && (blockAfterFlowRoot || rows.length > 0)) {
156
+ // P11 的真实成因:模板根 `[]` 是 flow 序列,其后再接分块行会让**整层**失效
157
+ return fail('flow root `[]` followed by block rows')
158
+ }
159
+ return { ok: true, rows, hadFlowRoot, skippedDeep }
160
+ }
161
+
162
+ /** insert 块新增的条目 id(覆盖行的判定用不到,留给报告「本层新增了哪些行」)。 */
163
+ export function insertedIds(rows) {
164
+ const out = []
165
+ for (const row of rows ?? []) {
166
+ if (row.insert !== true) continue
167
+ for (const item of row.entries ?? []) if (item.id) out.push(item.id)
168
+ }
169
+ return out
170
+ }
171
+
172
+ /**
173
+ * 读文件并解析。不存在 = `exists:false`(不算失败,交 P1 判缺);解析不了 = `ok:false`。
174
+ * @param {string} file
175
+ * @returns {{path:string, exists:boolean, text:string, parsed:ReturnType<typeof parsePatchText>}}
176
+ */
177
+ export function readPatchFile(file) {
178
+ try {
179
+ const text = fs.readFileSync(file, 'utf8')
180
+ return { path: file, exists: true, text, parsed: parsePatchText(text) }
181
+ } catch (e) {
182
+ const code = e && e.code
183
+ if (code === 'ENOENT') return { path: file, exists: false, text: '', parsed: { ok: true, rows: [], hadFlowRoot: false } }
184
+ return { path: file, exists: false, text: '', parsed: { ok: false, reason: String(code || (e && e.message)), rows: [], hadFlowRoot: false } }
185
+ }
186
+ }
187
+
188
+ /** 取某个 id 的覆盖行(后写的赢——与 applyEntryPatches 的顺序语义一致)。 */
189
+ export function findOverrideRow(parsed, id) {
190
+ if (!parsed || !Array.isArray(parsed.rows)) return undefined
191
+ const hits = parsed.rows.filter((row) => row.insert === false && row.id === id)
192
+ return hits.length === 0 ? undefined : hits[hits.length - 1]
193
+ }
194
+
195
+ /** 该 id 在本层是否被提到(覆盖行或 insert 的新条目)。 */
196
+ export function mentionsId(parsed, id) {
197
+ if (!parsed || !Array.isArray(parsed.rows)) return false
198
+ return parsed.rows.some((row) => (row.insert === false && row.id === id) || (row.insert === true && (row.entries ?? []).some((item) => item.id === id)))
199
+ }
package/src/report.js CHANGED
@@ -12,6 +12,7 @@ import { fileURLToPath } from 'node:url'
12
12
  export * from './core.js'
13
13
  import { activeLang, exitInstruction, setLang } from './core.js'
14
14
  import { detectLang, translator } from './i18n.js'
15
+ import { patchText } from './locales-patch.js'
15
16
 
16
17
  const HERE = path.dirname(fileURLToPath(import.meta.url))
17
18
 
@@ -83,3 +84,107 @@ export function cookieCleanerCommandText(stat, cfg = {}) {
83
84
  lines.push(t('cleanFooter'))
84
85
  return lines.join('\n')
85
86
  }
87
+
88
+ const VERDICT_KEY = Object.freeze({ ok: 'vOk', warn: 'vWarn', fail: 'vFail', skipped: 'vSkipped' })
89
+
90
+ /**
91
+ * 组装 patch 体检结果(命令面与面板共用同一份渲染,保证「按按钮」与「敲命令」不同案)。
92
+ * @param {object} result patch-guard check/plan 的返回
93
+ * @param {{lang?:string, platform?:string, outcome?:object, withPlan?:boolean}} [cfg]
94
+ */
95
+ export function patchReportText(result, cfg = {}) {
96
+ if (cfg.lang) setLang(cfg.lang)
97
+ const lang = cfg.lang ?? activeLang()
98
+ const L = (key, params) => patchText('text', key, lang, params)
99
+ const C = (code, params) => patchText('code', code, lang, params)
100
+ const lines = []
101
+
102
+ if (result.reason === 'no-config-editor') {
103
+ lines.push(L('title'))
104
+ lines.push(L('noService'))
105
+ return lines.join('\n')
106
+ }
107
+
108
+ // 无据档单独渲染:不能把「profile 不存在」混进「有偏差」的叙事里(也不给 nextFix 这种误导下一步)。
109
+ if (result.reason === 'missing-profile') {
110
+ lines.push(`${L('title')} — ${L('vSkipped')}`)
111
+ if (result.documentPath) lines.push(result.documentPath)
112
+ lines.push(L('missingProfile'))
113
+ return lines.join('\n')
114
+ }
115
+
116
+ lines.push(`${L('title')} — ${L(VERDICT_KEY[result.level] ?? 'vSkipped')}`)
117
+ if (result.documentPath) lines.push(result.documentPath)
118
+ if (result.offline === true) lines.push(L('offlineNote'))
119
+
120
+ const rows = result.rows ?? []
121
+ if (result.level === 'ok') {
122
+ // 结构无差异:一句话给肯定结论,不逐行刷「结构健康」(真机口径:用户要的是「注入正常」这个判定)。
123
+ lines.push(`\u2713 ${L('injectOk')}`)
124
+ }
125
+ else {
126
+ for (const row of rows) {
127
+ const label = row.rowId === 'connection' ? 'rowConnection' : 'rowWebserver'
128
+ lines.push(`\u25aa ${L(label)}: ${L(VERDICT_KEY[row.level] ?? 'vSkipped')}`)
129
+ for (const finding of row.findings ?? []) lines.push(` \u00b7 ${C(finding.code, finding.params)}`)
130
+ }
131
+ }
132
+
133
+ if (result.blocks !== undefined && result.blocks.length > 0) {
134
+ for (const block of result.blocks) {
135
+ lines.push('')
136
+ lines.push(L('planFor', { file: result.documentPath ?? 'cordis.patch.yml' }))
137
+ lines.push(block.block)
138
+ // 表达式被抄成字面量不在体检里刷屏,但处方里必须说清:哪些键原本会跟随上游、怎么拿回跟随形态。
139
+ if ((block.exprFrozen ?? []).length > 0) {
140
+ lines.push('')
141
+ lines.push(C('P9', { rowId: block.rowId, keys: block.exprFrozen }))
142
+ lines.push(L('exprFrozenHint'))
143
+ }
144
+ }
145
+ }
146
+
147
+ if ((result.rows ?? []).some((row) => row.rowId === 'webserver' && (row.findings ?? []).length > 0)) {
148
+ lines.push('')
149
+ lines.push(L('webserverNote'))
150
+ }
151
+ const conn = (result.rows ?? []).find((row) => row.rowId === 'connection')
152
+ if (conn?.actionable === true && cfg.outcome === undefined) {
153
+ lines.push('')
154
+ lines.push(L('nextFix'))
155
+ }
156
+ if (cfg.outcome !== undefined) lines.push('', patchOutcomeText(cfg.outcome, { lang }))
157
+ return lines.join('\n')
158
+ }
159
+
160
+ /** 修复/回滚结果的固定句式(kind 来自 patch-guard,不在此处二次判定)。 */
161
+ export function patchOutcomeText(outcome, cfg = {}) {
162
+ const lang = cfg.lang ?? activeLang()
163
+ const L = (key, params) => patchText('text', key, lang, params)
164
+ switch (outcome.kind) {
165
+ case 'fixed': return L('fixed', { changed: (outcome.changed ?? []).join(', ') })
166
+ + (outcome.retried === true ? ` (${L('vWarn')}: P12)` : '')
167
+ case 'noop': return L('noop')
168
+ case 'blocked': return L('blocked', { codes: (outcome.codes ?? []).join(', ') })
169
+ case 'failed': return L('failed', { message: outcome.message ?? 'unknown' })
170
+ case 'unverified': return L('failed', { message: `effective=${String(outcome.effective)}` })
171
+ case 'reverted': return L('reverted', { changed: (outcome.changed ?? []).join(', ') })
172
+ + ((outcome.rows ?? []).length > 1 ? ` (${(outcome.rows ?? []).join(', ')})` : '')
173
+ + ((outcome.failed ?? []).length > 0 ? ` (${L('failed', { message: (outcome.failed ?? []).map((f) => f.rowId).join(', ') })})` : '')
174
+ // 端口:写的是什么表达式、监听现在到底在哪个端口,全部回传真实数据(不拿“点了”当“改好了”)。
175
+ case 'port-applied': {
176
+ const lines = [L('portApplied', { expr: outcome.expr ?? String(outcome.port), port: outcome.port })]
177
+ if (outcome.hotApplied === true) lines.push(L('portHot'))
178
+ else if (outcome.hotApplied === false) lines.push(L('portRestart'))
179
+ else lines.push(L('portUnknown'))
180
+ // 无论哪档,端口一旦生效旧地址就不可用:补一句同步提醒(热生效时尤其关键)。
181
+ lines.push(L('portSwitchWarn'))
182
+ return lines.join('\n') + (outcome.retried === true ? ` (${L('vWarn')}: P12)` : '')
183
+ }
184
+ case 'port-busy': return L('portBusy', { port: outcome.port })
185
+ case 'invalid-port': return L('portInvalid', { minimum: outcome.minimum, maximum: outcome.maximum, got: String(outcome.got) })
186
+ case 'no-snapshot': return L('noSnapshot')
187
+ case 'no-editor': return L('noService')
188
+ default: return L('failed', { message: outcome.kind ?? 'unknown' })
189
+ }
190
+ }