dsh-cookie-cleaner 0.1.1 → 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/CHANGELOG.md +77 -0
- package/README.md +69 -12
- package/dsh.plugin.json +2 -2
- package/lib/client.js +565 -0
- package/lib/client.js.map +1 -0
- package/locale/de.json +1 -1
- package/locale/en.json +1 -1
- package/locale/es.json +1 -1
- package/locale/fr.json +1 -1
- package/locale/it.json +1 -1
- package/locale/ja.json +1 -1
- package/locale/ko.json +1 -1
- package/locale/ru.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +30 -5
- package/scripts/gen-locales.mjs +9 -9
- package/scripts/sync-hosts.mjs +25 -0
- package/src/api-routes.js +125 -0
- package/src/cli.js +87 -3
- package/src/client/card.tsx +195 -0
- package/src/client/index.ts +129 -0
- package/src/client/locales.ts +80 -0
- package/src/client/routes.ts +83 -0
- package/src/index.js +81 -10
- package/src/locales-patch.js +200 -0
- package/src/patch-guard.js +462 -0
- package/src/patch-model.js +312 -0
- package/src/patch-read.js +199 -0
- package/src/report.js +105 -0
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — patch 体检/修复的宿主半适配层。
|
|
3
|
+
*
|
|
4
|
+
* 职责边界:这里只做「取数 + 调官方 configEditor + 落快照」,判定全在 `patch-model.js`,
|
|
5
|
+
* 文案全在 `report.js` + `locales-patch.js`。写动作**一律走 `configEditor.edit()`**,
|
|
6
|
+
* 不自己拼 YAML——官方通道自带文件锁、目标插件 Config schema 校验、home 影子检查、
|
|
7
|
+
* 原子写与 reconcile 失败回滚(源码依据见 `.agents/plans/cookie-patch-guard/findings.md` §6)。
|
|
8
|
+
*
|
|
9
|
+
* 三条实测约束(0.2.1-rc.5,全部踩过):
|
|
10
|
+
* 1. 冷启动 `ctx.get('configEditor')` 是 undefined ⇒ 只能靠 scoped inject 的回调时机;
|
|
11
|
+
* 2. 在 apply 执行链上直接 `edit()` 抛 `HMR transactions cannot be nested` ⇒ 写只能发生在
|
|
12
|
+
* 用户触发的请求/命令回调链上,并对该错误做**一次退避重试**(P12),不硬失败;
|
|
13
|
+
* 3. 写后 HMR 会热应用,无需重启;但必须回读 effective 才算「修好了」。
|
|
14
|
+
*/
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import net from 'node:net'
|
|
17
|
+
import os from 'node:os'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import { MANAGED_ROWS, PORT_WRITE, aggregateAll, assessRow, isValidPort, nextConfigFor, nextPortConfig } from './patch-model.js'
|
|
20
|
+
import { findOverrideRow, parsePatchText, readPatchFile } from './patch-read.js'
|
|
21
|
+
|
|
22
|
+
/** 嵌套事务错误:热重载期间的正常现象,不是配置问题。 */
|
|
23
|
+
const NESTED_ERROR = /HMR transactions cannot be nested/i
|
|
24
|
+
const SNAPSHOT_DIR = 'cookie-cleaner'
|
|
25
|
+
|
|
26
|
+
/** DSH home(快照落这里,与 profile 目录解耦,删格不丢回滚能力)。 */
|
|
27
|
+
export function dshHome(env = process.env, homedir = os.homedir()) {
|
|
28
|
+
const explicit = String(env.DSH_HOME ?? '').trim()
|
|
29
|
+
return explicit !== '' ? explicit : path.join(homedir, '.dsh')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 端口占用探针。**只探不占**:用 `connect` 看有人应答就算在用(而不是 bind 一个测试监听
|
|
34
|
+
* 去抢端口)。目的是把“与你代理/科学上网工具常用端口撞车”这句话变成数据而不是猜测。
|
|
35
|
+
* @returns {'busy'|'free'|'unknown'}
|
|
36
|
+
*/
|
|
37
|
+
export function probePort(port, host = '127.0.0.1', timeoutMs = 700) {
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
if (!isValidPort(port)) return resolve('unknown')
|
|
40
|
+
let settled = false
|
|
41
|
+
const done = (value) => { if (!settled) { settled = true; resolve(value) } }
|
|
42
|
+
const socket = net.connect({ host, port })
|
|
43
|
+
const timer = setTimeout(() => { socket.destroy(); done('free') }, timeoutMs)
|
|
44
|
+
socket.once('connect', () => { clearTimeout(timer); socket.destroy(); done('busy') })
|
|
45
|
+
// 拒连/网络不可达 = 没人听;其余(权限、沙箱限制等)是无据,不假装知道
|
|
46
|
+
socket.once('error', (e) => {
|
|
47
|
+
clearTimeout(timer)
|
|
48
|
+
const code = String(e && e.code)
|
|
49
|
+
done(code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ECONNRESET' ? 'free' : 'unknown')
|
|
50
|
+
})
|
|
51
|
+
socket.once('timeout', () => { socket.destroy(); done('free') })
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 快照的 profile 身份。**必须按 profile 隔离**:
|
|
57
|
+
* 真机串台过一次——在隔离格跑的那次 fix 把快照留在全局单文件里,
|
|
58
|
+
* 另一个 profile 的面板于是显示了别人的「上次修复」,更糟的是点「回滚」
|
|
59
|
+
* 会把**别的 profile** 的旧 config 写进当前 profile。所有一旧的全局快照不再读。
|
|
60
|
+
* 判据取 profile 目录名(`<home>/profiles/<name>/cordis.patch.yml`),推不出就用父目录名。
|
|
61
|
+
*/
|
|
62
|
+
export function snapshotKey(profileFile = '') {
|
|
63
|
+
const parts = String(profileFile).split(/[\\/]+/).filter(Boolean)
|
|
64
|
+
const at = parts.lastIndexOf('profiles')
|
|
65
|
+
if (at >= 0 && parts[at + 1] !== undefined) return String(parts[at + 1])
|
|
66
|
+
return parts.length > 1 ? String(parts[parts.length - 2]) : 'default'
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function snapshotFile(homeDir = dshHome(), profileFile = '') {
|
|
70
|
+
return path.join(homeDir, SNAPSHOT_DIR, `patch-snapshot--${snapshotKey(profileFile)}.json`)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 深拷贝成 JSON 安全形态(`{__jsExpr}` 是普通对象,能直接过 JSON)。 */
|
|
74
|
+
function plain(value) {
|
|
75
|
+
if (value === undefined) return undefined
|
|
76
|
+
try { return JSON.parse(JSON.stringify(value)) } catch { return undefined }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function readSnapshot(file, fsModule) {
|
|
80
|
+
try {
|
|
81
|
+
const raw = JSON.parse(fsModule.readFileSync(file, 'utf8'))
|
|
82
|
+
if (raw === null || typeof raw !== 'object') return undefined
|
|
83
|
+
// v2:`{rows: {<rowId>: {config…}}}`;v1(旧形式):单行 `{rowId, config…}`。
|
|
84
|
+
if (raw.rows !== null && typeof raw.rows === 'object') return raw
|
|
85
|
+
if (raw.config !== null && typeof raw.config === 'object') {
|
|
86
|
+
const rowId = typeof raw.rowId === 'string' ? raw.rowId : 'connection'
|
|
87
|
+
return { version: 2, profile: raw.profile, generatedAt: raw.generatedAt, rows: { [rowId]: raw } }
|
|
88
|
+
}
|
|
89
|
+
return undefined
|
|
90
|
+
} catch { return undefined }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 把新一次的“写前值”并写入快照(cookie 寿命与端口是两个独立动作,各自回到各自的前值)。 */
|
|
94
|
+
function keepSnapshotRow(file, rowId, data, fsModule) {
|
|
95
|
+
const base = readSnapshot(file, fsModule) ?? { version: 2, rows: {} }
|
|
96
|
+
base.rows = { ...base.rows, [rowId]: data }
|
|
97
|
+
base.profile = data.profile ?? base.profile
|
|
98
|
+
base.generatedAt = data.generatedAt ?? base.generatedAt
|
|
99
|
+
writeSnapshot(file, base, fsModule)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function writeSnapshot(file, data, fsModule) {
|
|
103
|
+
fsModule.mkdirSync(path.dirname(file), { recursive: true })
|
|
104
|
+
fsModule.writeFileSync(file, JSON.stringify(data, null, 2), 'utf8')
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 造一个守卫。所有外部依赖都注入,方便单测与 CLI 侧共用判定。
|
|
109
|
+
* @param {{
|
|
110
|
+
* getEditor: () => any,
|
|
111
|
+
* fs?: typeof import('node:fs'),
|
|
112
|
+
* env?: Record<string,string|undefined>,
|
|
113
|
+
* homeDir?: string,
|
|
114
|
+
* targetDays?: number,
|
|
115
|
+
* guardMode?: 'literal'|'expression',
|
|
116
|
+
* wait?: (ms:number) => Promise<void>,
|
|
117
|
+
* now?: () => number,
|
|
118
|
+
* }} deps
|
|
119
|
+
*/
|
|
120
|
+
export function createPatchGuard(deps) {
|
|
121
|
+
const {
|
|
122
|
+
getEditor,
|
|
123
|
+
fs: fsModule = fs,
|
|
124
|
+
env = process.env,
|
|
125
|
+
homeDir = dshHome(env),
|
|
126
|
+
wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
127
|
+
now = () => Date.now(),
|
|
128
|
+
probe = (port) => probePort(port),
|
|
129
|
+
} = deps
|
|
130
|
+
/** 可覆盖的目标档位由调用方(命令/路由)每次传入,避免守卫里存状态。 */
|
|
131
|
+
const state = { homeDir }
|
|
132
|
+
/** 快照路径按**当前 profile** 算(documentPath 只有 editor 就绪后才知道,不能构造时定死)。 */
|
|
133
|
+
function snapFile() {
|
|
134
|
+
const ce = getEditor()
|
|
135
|
+
const doc = ce !== undefined && typeof ce.documentPath === 'string' ? ce.documentPath : ''
|
|
136
|
+
return snapshotFile(homeDir, doc)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 组合 configEditor 的运行态与 profile 文件的字面态,喂给内核。 */
|
|
140
|
+
function buildInput(rowId, ce, options) {
|
|
141
|
+
const spec = MANAGED_ROWS[rowId]
|
|
142
|
+
const entry = ce.entries().find((item) => item.options.id === spec.id)
|
|
143
|
+
const configuration = (typeof ce.configuration === 'function' ? ce.configuration() : []).find((row) => row.entry.options.id === spec.id)
|
|
144
|
+
const profileFile = ce.documentPath
|
|
145
|
+
const profileRead = readPatchFileWith(fsModule, profileFile)
|
|
146
|
+
const homeRead = readPatchFileWith(fsModule, path.join(state.homeDir, 'cordis.patch.yml'))
|
|
147
|
+
|
|
148
|
+
// 覆盖行以**文件**为准:name 写错的行会被宿主静默跳过,此时 configuration().override 是空的,
|
|
149
|
+
// 只有文件里看得到那行——P2 的价值恰恰在于「把看不见的失效说出来」。
|
|
150
|
+
const fileRow = profileRead.parsed.ok ? findOverrideRow(profileRead.parsed, spec.id) : undefined
|
|
151
|
+
const overrideRow = fileRow !== undefined
|
|
152
|
+
? { name: fileRow.name, config: fileRow.config ?? {} }
|
|
153
|
+
: (configuration !== undefined && Object.keys(configuration.override ?? {}).length > 0
|
|
154
|
+
? { name: configuration.entry.options.name, config: configuration.override }
|
|
155
|
+
: undefined)
|
|
156
|
+
|
|
157
|
+
return {
|
|
158
|
+
rowId: spec.id,
|
|
159
|
+
entryFound: entry !== undefined,
|
|
160
|
+
overrideRow,
|
|
161
|
+
inherited: configuration?.inherited ?? {},
|
|
162
|
+
effective: entry?.options?.config ?? configuration?.entry?.options?.config ?? {},
|
|
163
|
+
targetDays: spec.id === 'connection' ? options.targetDays : undefined,
|
|
164
|
+
shadowedBy: homeRead.exists && homeRead.parsed.ok && findOverrideRow(homeRead.parsed, spec.id) !== undefined ? 'home' : null,
|
|
165
|
+
// 整层合法性:profile 层解析不了就是 P11;home 层解析不了只是看不见影子(不谎报)
|
|
166
|
+
fileParse: profileRead.exists ? profileRead.parsed : { ok: true, rows: [], hadFlowRoot: false },
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function check(options = {}) {
|
|
171
|
+
const ce = getEditor()
|
|
172
|
+
if (ce === undefined || typeof ce.entries !== 'function') {
|
|
173
|
+
return { level: 'skipped', reason: 'no-config-editor', rows: [], documentPath: '' }
|
|
174
|
+
}
|
|
175
|
+
const opts = { targetDays: options.targetDays ?? 1, ...options }
|
|
176
|
+
const rows = Object.keys(MANAGED_ROWS).map((rowId) => assessRow(buildInput(rowId, ce, opts)))
|
|
177
|
+
const documentPath = typeof ce.documentPath === 'string' ? ce.documentPath : ''
|
|
178
|
+
// 上次修复的可审计信息:面板重开也该看得到,不能只在点完按钮那一瞬存在
|
|
179
|
+
const snap = readSnapshot(snapFile(), fsModule)
|
|
180
|
+
const connSnap = snap?.rows?.connection
|
|
181
|
+
const lastFix = connSnap === undefined ? undefined : {
|
|
182
|
+
at: connSnap.generatedAt ?? null,
|
|
183
|
+
beforeDays: connSnap.config?.cookieMaxAgeDays,
|
|
184
|
+
targetDays: connSnap.targetDays,
|
|
185
|
+
}
|
|
186
|
+
// 端口同理:面板重开也该看得“上次把端口改成了什么、现在听的是哪个”,不能只在点完那一瞬存在。
|
|
187
|
+
const portSnap = snap?.rows?.webserver
|
|
188
|
+
const lastPort = portSnap === undefined ? undefined : {
|
|
189
|
+
at: portSnap.generatedAt ?? null,
|
|
190
|
+
before: portSnap.config?.port,
|
|
191
|
+
port: portSnap.port,
|
|
192
|
+
}
|
|
193
|
+
return { ...aggregateAll(rows), documentPath, rows, lastFix, lastPort, checkedAt: new Date(now()).toISOString() }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 只给用户看的粘贴块(webserver 行、以及 CLI 侧无法写时的处方)。 */
|
|
197
|
+
function plan(options = {}) {
|
|
198
|
+
const result = check(options)
|
|
199
|
+
const ce = getEditor()
|
|
200
|
+
if (ce === undefined) return { ...result, blocks: [] }
|
|
201
|
+
// 有偏差的行要给粘贴块;**表达式被抄成字面量**的行也算(它不改档位,但只有这里能提)。
|
|
202
|
+
const blocks = result.rows
|
|
203
|
+
.filter((row) => row.findings.length > 0 || (row.exprFrozen ?? []).length > 0)
|
|
204
|
+
.map((row) => {
|
|
205
|
+
const spec = MANAGED_ROWS[row.rowId]
|
|
206
|
+
const entry = ce.entries().find((item) => item.options.id === spec.id)
|
|
207
|
+
const configuration = (ce.configuration() ?? []).find((item) => item.entry.options.id === spec.id)
|
|
208
|
+
return {
|
|
209
|
+
rowId: row.rowId,
|
|
210
|
+
writable: spec.writable,
|
|
211
|
+
exprFrozen: row.exprFrozen ?? [],
|
|
212
|
+
block: nextBlockFor(row.rowId, configuration?.inherited ?? {}, entry?.options?.config ?? {}, options),
|
|
213
|
+
}
|
|
214
|
+
})
|
|
215
|
+
return { ...result, documentPath: ce.documentPath ?? '', blocks }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function nextBlockFor(rowId, inherited, current, options) {
|
|
219
|
+
// 表达式档:把 bundle 层原有的表达式还原回去(表达式串取自 inherited,绝不硬编码)
|
|
220
|
+
const merged = { ...inherited, ...current }
|
|
221
|
+
if (options.guardMode === 'expression') {
|
|
222
|
+
for (const [key, value] of Object.entries(inherited)) {
|
|
223
|
+
if (value !== null && typeof value === 'object' && typeof value.__jsExpr === 'string') merged[key] = value
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (rowId === 'connection' && options.targetDays !== undefined) merged.cookieMaxAgeDays = options.targetDays
|
|
227
|
+
return renderBlock(rowId, merged)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function attemptEdit(entry, next) {
|
|
231
|
+
const ce = getEditor()
|
|
232
|
+
try {
|
|
233
|
+
await ce.edit(entry, () => next)
|
|
234
|
+
return { ok: true, nested: false }
|
|
235
|
+
} catch (e) {
|
|
236
|
+
const message = String(e && e.message ? e.message : e)
|
|
237
|
+
if (!NESTED_ERROR.test(message)) return { ok: false, message, nested: false }
|
|
238
|
+
// P12:热重载正在进行,退避一次再试;仍失败就如实报「稍后再点」,不谎报成功
|
|
239
|
+
await wait(400)
|
|
240
|
+
try {
|
|
241
|
+
await ce.edit(ce.entries().find((row) => row.options.id === entry.options.id), () => next)
|
|
242
|
+
return { ok: true, nested: true, retried: true }
|
|
243
|
+
} catch (e2) {
|
|
244
|
+
return { ok: false, message: String(e2 && e2.message ? e2.message : e2), nested: true }
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* 修复:把 connection 行的 cookieMaxAgeDays 拉到目标档,其余键按运行态原样保留。
|
|
251
|
+
* 判定为不可动作(P2/P4/P6/P10/P11)时**一次都不写**。
|
|
252
|
+
*/
|
|
253
|
+
async function fix(options = {}) {
|
|
254
|
+
const result = check(options)
|
|
255
|
+
const target = result.rows.find((row) => row.rowId === MANAGED_ROWS.connection.id)
|
|
256
|
+
if (target === undefined) return { kind: 'blocked', reason: 'no-connection-row', result }
|
|
257
|
+
if (!target.actionable) {
|
|
258
|
+
return { kind: 'blocked', codes: target.findings.map((f) => f.code), level: target.level, result }
|
|
259
|
+
}
|
|
260
|
+
const ce = getEditor()
|
|
261
|
+
const entry = ce.entries().find((row) => row.options.id === MANAGED_ROWS.connection.id)
|
|
262
|
+
if (entry === undefined) return { kind: 'blocked', codes: ['P10'], result }
|
|
263
|
+
|
|
264
|
+
const before = plain(entry.options.config ?? {})
|
|
265
|
+
const spec = MANAGED_ROWS.connection
|
|
266
|
+
const configuration = (ce.configuration() ?? []).find((row) => row.entry.options.id === spec.id)
|
|
267
|
+
const { next, changed } = nextConfigFor({
|
|
268
|
+
current: entry.options.config ?? {},
|
|
269
|
+
targetDays: options.targetDays ?? 1,
|
|
270
|
+
guardMode: options.guardMode,
|
|
271
|
+
inherited: configuration?.inherited ?? {},
|
|
272
|
+
})
|
|
273
|
+
if (changed.length === 0) return { kind: 'noop', result, before }
|
|
274
|
+
|
|
275
|
+
const written = await attemptEdit(entry, next)
|
|
276
|
+
if (!written.ok) return { kind: 'failed', message: written.message, nested: written.nested === true, result }
|
|
277
|
+
|
|
278
|
+
try {
|
|
279
|
+
keepSnapshotRow(snapFile(), spec.id, { name: spec.name, profile: snapshotKey(ce.documentPath ?? ''), config: before, at: now(), generatedAt: new Date(now()).toISOString(), targetDays: options.targetDays ?? 1 }, fsModule)
|
|
280
|
+
} catch { /* 快照失败不影响已落盘的修复,只是少了回滚 */ }
|
|
281
|
+
|
|
282
|
+
const after = ce.entries().find((row) => row.options.id === spec.id)
|
|
283
|
+
const effective = after?.options?.config?.cookieMaxAgeDays
|
|
284
|
+
const applied = effective === (options.targetDays ?? 1)
|
|
285
|
+
// 写成功后回传**重新体检**的结果:把写前的 `result` 丢给面板会让它显示“已写入”同时
|
|
286
|
+
// 又挂着“缺行・有偏差”(真机看到的就是这个矛盾)。
|
|
287
|
+
const fresh = check(options)
|
|
288
|
+
return { kind: applied ? 'fixed' : 'unverified', changed, before, beforeValue: before?.cookieMaxAgeDays, effective, applied, retried: written.retried === true, snapshotFile: snapFile(), snapshotAt: new Date(now()).toISOString(), result: fresh }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* 应用端口:只改 webserver 行的 `port`,且**永远写成表达式**(带数字字面量就是把 P8 自己造出来)。
|
|
293
|
+
* 不并进「修复」:端口属启动行为面,必须用户显式点。目标值不存默认:非法/未给就拒。
|
|
294
|
+
* 写前用探针看目标端口在本机是不是已经被占(与代理工具撞车就是这个场景),占用就不写;
|
|
295
|
+
* 写后“运行中听到的是哪个端口”也用探针回答,不拿配置猜热生效。
|
|
296
|
+
*/
|
|
297
|
+
async function applyPort(options = {}) {
|
|
298
|
+
const port = Number(options.port)
|
|
299
|
+
if (!isValidPort(port)) return { kind: 'invalid-port', got: options.port, minimum: PORT_WRITE.minimum, maximum: PORT_WRITE.maximum }
|
|
300
|
+
const result = check(options)
|
|
301
|
+
const row = result.rows.find((item) => item.rowId === PORT_WRITE.rowId)
|
|
302
|
+
if (row === undefined) return { kind: 'blocked', reason: 'no-webserver-row', result }
|
|
303
|
+
if (row.blocked === true) return { kind: 'blocked', codes: row.findings.map((f) => f.code), level: row.level, result }
|
|
304
|
+
const ce = getEditor()
|
|
305
|
+
const entry = ce.entries().find((item) => item.options.id === PORT_WRITE.rowId)
|
|
306
|
+
if (entry === undefined) return { kind: 'blocked', codes: ['P10'], result }
|
|
307
|
+
|
|
308
|
+
const configuration = (ce.configuration() ?? []).find((item) => item.entry.options.id === PORT_WRITE.rowId)
|
|
309
|
+
const { next, changed, expr } = nextPortConfig({ current: entry.options.config ?? {}, inherited: configuration?.inherited ?? {}, port })
|
|
310
|
+
if (changed.length === 0) return { kind: 'noop', port, expr, result }
|
|
311
|
+
|
|
312
|
+
const state = await probe(port)
|
|
313
|
+
if (state === 'busy') return { kind: 'port-busy', port, expr, probe: state, result }
|
|
314
|
+
|
|
315
|
+
const before = plain(entry.options.config ?? {})
|
|
316
|
+
const beforePort = typeof before?.[PORT_WRITE.key] === 'number' ? before[PORT_WRITE.key] : undefined
|
|
317
|
+
const written = await attemptEdit(entry, next)
|
|
318
|
+
if (!written.ok) return { kind: 'failed', message: written.message, nested: written.nested === true, result }
|
|
319
|
+
|
|
320
|
+
try {
|
|
321
|
+
keepSnapshotRow(snapFile(), PORT_WRITE.rowId, { name: PORT_WRITE.name, profile: snapshotKey(ce.documentPath ?? ''), config: before, at: now(), generatedAt: new Date(now()).toISOString(), port }, fsModule)
|
|
322
|
+
} catch { /* 同上:快照失败不谎报写入失败 */ }
|
|
323
|
+
|
|
324
|
+
const after = ce.entries().find((item) => item.options.id === PORT_WRITE.rowId)
|
|
325
|
+
const live = after?.options?.config?.[PORT_WRITE.key]
|
|
326
|
+
// 热生效与否看监听,不看配置:新端口有人听 = 已切;只有旧端口有人听 = 下次启动生效。
|
|
327
|
+
const nowListening = await probe(port)
|
|
328
|
+
const oldListening = beforePort === undefined ? 'unknown' : await probe(beforePort)
|
|
329
|
+
const hotApplied = nowListening === 'busy' ? true : oldListening === 'busy' ? false : undefined
|
|
330
|
+
return {
|
|
331
|
+
kind: 'port-applied',
|
|
332
|
+
port,
|
|
333
|
+
expr,
|
|
334
|
+
changed,
|
|
335
|
+
before,
|
|
336
|
+
beforePort,
|
|
337
|
+
live,
|
|
338
|
+
hotApplied,
|
|
339
|
+
probeState: state,
|
|
340
|
+
retried: written.retried === true,
|
|
341
|
+
snapshotFile: snapFile(),
|
|
342
|
+
snapshotAt: new Date(now()).toISOString(),
|
|
343
|
+
result: check(options),
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** 回到写之前的配置(快照按行存,一次回滚把各行各自回前值;缺失就明说,不猜)。 */
|
|
348
|
+
async function revert() {
|
|
349
|
+
const ce = getEditor()
|
|
350
|
+
if (ce === undefined || typeof ce.edit !== 'function') return { kind: 'no-editor' }
|
|
351
|
+
const snapshot = readSnapshot(snapFile(), fsModule)
|
|
352
|
+
if (snapshot === undefined || Object.keys(snapshot.rows ?? {}).length === 0) return { kind: 'no-snapshot', snapshotFile: snapFile() }
|
|
353
|
+
|
|
354
|
+
const restored = []
|
|
355
|
+
const failed = []
|
|
356
|
+
let lastChanged = []
|
|
357
|
+
let connEffective
|
|
358
|
+
for (const [rowId, saved] of Object.entries(snapshot.rows)) {
|
|
359
|
+
const entry = ce.entries().find((row) => row.options.id === rowId)
|
|
360
|
+
if (entry === undefined) { failed.push({ rowId, code: 'P10' }); continue }
|
|
361
|
+
const current = plain(entry.options.config ?? {})
|
|
362
|
+
const written = await attemptEdit(entry, saved.config)
|
|
363
|
+
if (!written.ok) { failed.push({ rowId, message: written.message }); continue }
|
|
364
|
+
restored.push(rowId)
|
|
365
|
+
lastChanged = diffKeys(current, saved.config)
|
|
366
|
+
if (rowId === MANAGED_ROWS.connection.id) {
|
|
367
|
+
connEffective = ce.entries().find((row) => row.options.id === rowId)?.options?.config?.cookieMaxAgeDays
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (restored.length === 0) return { kind: 'failed', message: failed[0]?.message ?? 'nothing restored', failed }
|
|
371
|
+
return {
|
|
372
|
+
kind: 'reverted',
|
|
373
|
+
changed: lastChanged,
|
|
374
|
+
rows: restored,
|
|
375
|
+
failed,
|
|
376
|
+
effective: connEffective,
|
|
377
|
+
restoredFrom: snapshot.generatedAt ?? null,
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return { check, plan, fix, revert, applyPort, state }
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* 离线(客户端已关、宿主不存在)只能查**文件层**:运行态与 bundle 层都读不到,
|
|
386
|
+
* 所以 P5/P7/P9 这三类需要 bundle/运行态对比的规则不参与判定。宁缺毋滥:
|
|
387
|
+
* 能定死的是「行在不在、name 对不对、值合不合法、有没有被 home 层盖住、整层语法能不能解」。
|
|
388
|
+
* 与面板共用同一个 `assessRow`,绝不另开一套判定。
|
|
389
|
+
* @param {{profileFile:string, homeFile?:string, targetDays?:number, fs?:typeof import('node:fs')}} options
|
|
390
|
+
*/
|
|
391
|
+
export function offlineCheck(options) {
|
|
392
|
+
const { profileFile, homeFile = path.join(dshHome(), 'cordis.patch.yml'), targetDays = 1, fs: fsModule = fs } = options
|
|
393
|
+
const profile = readPatchFileWith(fsModule, profileFile)
|
|
394
|
+
// 「profile 根本不在这个位置」与「profile 在、但没这一行」是两回事:前者**无据**(skipped),
|
|
395
|
+
// 后者才是真偏差(P1)。把前者判成缺行会把「用户敲错 profile 名」变成一条误导性的
|
|
396
|
+
// 「cookie 会一直存活」异常,还会让退出码假绿(黑名单纪律:没真读到内容就不许 0)。
|
|
397
|
+
// 目录在、仅文件缺(新建 profile 还没写过 patch)仍走 P1——那是可修的真缺陷。
|
|
398
|
+
if (profile.exists === false && !fsModule.existsSync(path.dirname(profileFile))) {
|
|
399
|
+
return {
|
|
400
|
+
level: 'skipped',
|
|
401
|
+
rows: [],
|
|
402
|
+
actionable: false,
|
|
403
|
+
reason: 'missing-profile',
|
|
404
|
+
documentPath: profileFile,
|
|
405
|
+
homePath: homeFile,
|
|
406
|
+
offline: true,
|
|
407
|
+
checkedAt: new Date().toISOString(),
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const home = readPatchFileWith(fsModule, homeFile)
|
|
411
|
+
const rows = Object.keys(MANAGED_ROWS).map((rowId) => {
|
|
412
|
+
const spec = MANAGED_ROWS[rowId]
|
|
413
|
+
const fileRow = profile.parsed.ok ? findOverrideRow(profile.parsed, spec.id) : undefined
|
|
414
|
+
return assessRow({
|
|
415
|
+
rowId: spec.id,
|
|
416
|
+
overrideRow: fileRow === undefined ? undefined : { name: fileRow.name, config: fileRow.config ?? {} },
|
|
417
|
+
inherited: {},
|
|
418
|
+
effective: {},
|
|
419
|
+
targetDays: spec.id === 'connection' ? targetDays : undefined,
|
|
420
|
+
shadowedBy: home.exists && home.parsed.ok && findOverrideRow(home.parsed, spec.id) !== undefined ? 'home' : null,
|
|
421
|
+
fileParse: profile.exists ? profile.parsed : { ok: true, rows: [], hadFlowRoot: false },
|
|
422
|
+
})
|
|
423
|
+
})
|
|
424
|
+
return { ...aggregateAll(rows), documentPath: profileFile, homePath: homeFile, offline: true, checkedAt: new Date().toISOString() }
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function diffKeys(a, b) {
|
|
428
|
+
const keys = new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])
|
|
429
|
+
return [...keys].filter((key) => JSON.stringify(a?.[key]) !== JSON.stringify(b?.[key]))
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function readPatchFileWith(fsModule, file) {
|
|
433
|
+
if (typeof file !== 'string' || file === '') {
|
|
434
|
+
return { path: file, exists: false, text: '', parsed: { ok: true, rows: [], hadFlowRoot: false } }
|
|
435
|
+
}
|
|
436
|
+
if (fsModule === fs) return readPatchFile(file)
|
|
437
|
+
// 注入替身(单测/多实例)时走等价路径,**同一份** parsePatchText,不另开一套解析
|
|
438
|
+
let text = ''
|
|
439
|
+
let exists = true
|
|
440
|
+
try {
|
|
441
|
+
text = fsModule.readFileSync(file, 'utf8')
|
|
442
|
+
} catch (e) {
|
|
443
|
+
if (e && e.code === 'ENOENT') { exists = false } else {
|
|
444
|
+
return { path: file, exists: false, text: '', parsed: { ok: false, reason: String((e && e.code) || (e && e.message)), rows: [], hadFlowRoot: false } }
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return { path: file, exists, text, parsed: exists ? parsePatchText(text) : { ok: true, rows: [], hadFlowRoot: false } }
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** 把合并后的配置渲染成 YAML 块(与 patch-model 的 renderPlanBlock 同语义,此处避免循环依赖)。 */
|
|
451
|
+
function renderBlock(rowId, merged) {
|
|
452
|
+
const spec = MANAGED_ROWS[rowId]
|
|
453
|
+
const lines = [`- id: ${spec.id}`, ` name: '${spec.name}'`, ' config:']
|
|
454
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
455
|
+
if (value === undefined) continue
|
|
456
|
+
if (value !== null && typeof value === 'object' && typeof value.__jsExpr === 'string') lines.push(` ${key}: !!js ${value.__jsExpr}`)
|
|
457
|
+
else if (Array.isArray(value)) lines.push(` ${key}: ${value.length === 0 ? '[]' : JSON.stringify(value)}`)
|
|
458
|
+
else if (typeof value === 'string') lines.push(` ${key}: '${value}'`)
|
|
459
|
+
else lines.push(` ${key}: ${value}`)
|
|
460
|
+
}
|
|
461
|
+
return lines.join('\n')
|
|
462
|
+
}
|