dsh-plugin-slim 0.0.0-stage → 0.1.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/lib/patch.js ADDED
@@ -0,0 +1,797 @@
1
+ /**
2
+ * Surgical cordis.patch.yml editing, YAML validation and reversible snapshots.
3
+ *
4
+ * Every write to the user's patch file must:
5
+ * 1. touch only a single `disabled: true|false` row of the matching top-level
6
+ * `- id: <entryId>` block, preserving comments, blank lines, inline comments,
7
+ * !!js expressions and every unrelated config row verbatim;
8
+ * 2. be read back with yaml.parseDocument: any doc.errors or a non-sequence
9
+ * top level refuses the write. `!!js/function` / `!!js/regexp` tags on other
10
+ * rows only produce TAG_RESOLVE_FAILED warnings (yaml v2 never evaluates
11
+ * the JS) and must not block the edit;
12
+ * 3. be snapshotted to <backupDir>/snapshots/<id>.json before the first byte is
13
+ * written, then written atomically (.tmp + rename, with a copy fallback for
14
+ * Windows EPERM/EXDEV/EEXIST) and stay restorable, idempotently.
15
+ *
16
+ * @module dsh-plugin-slim/patch
17
+ */
18
+ import { randomBytes } from 'node:crypto'
19
+ import { constants as fsConstants } from 'node:fs'
20
+ import { access, copyFile, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
21
+ import { dirname, join } from 'node:path'
22
+ import { isSeq, parseDocument } from 'yaml'
23
+
24
+ /** Placeholder content used when the patch file is created from scratch. */
25
+ const EMPTY_SEQUENCE = '[]\n'
26
+
27
+ /** How many operation snapshots are retained. */
28
+ const MAX_SNAPSHOTS = 20
29
+
30
+ /** Snapshot ids are used as file names: no path separators, no traversal. */
31
+ const SNAPSHOT_ID_PATTERN = new RegExp('^[A-Za-z0-9_-]+$')
32
+
33
+ /** Entry ids that can be written as a plain YAML scalar. */
34
+ const SAFE_ENTRY_ID = new RegExp('^[A-Za-z0-9_.:@/-]+$')
35
+
36
+ /** A top-level sequence item line (column 0, dash, whitespace or EOL). */
37
+ const TOP_LEVEL_ITEM = new RegExp('^-([ \t]|$)')
38
+
39
+ /** One sequence item's first key: - key: rest */
40
+ const ITEM_KEY = new RegExp('^-([ \t]+)([A-Za-z_][A-Za-z0-9_-]*)([ \t]*):(.*)$')
41
+
42
+ /** A mapping property line inside a block. */
43
+ const PROPERTY_LINE = new RegExp('^([ \t]+)([A-Za-z_][A-Za-z0-9_-]*)[ \t]*:(.*)$')
44
+
45
+ /** Default readers/writers; tests may inject a subset through { io }. */
46
+ const DEFAULT_IO = Object.freeze({
47
+ access,
48
+ copyFile,
49
+ mkdir,
50
+ readFile,
51
+ readdir,
52
+ rename,
53
+ rm,
54
+ writeFile,
55
+ })
56
+
57
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
58
+ function isRecord(value) {
59
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
60
+ }
61
+
62
+ /** @param {unknown} value @returns {string} */
63
+ function textOf(value) {
64
+ return typeof value === 'string' ? value : ''
65
+ }
66
+
67
+ /** @param {unknown} error @returns {string} */
68
+ function errorText(error) {
69
+ if (error instanceof Error && error.message !== '') return error.message
70
+ const text = String(error)
71
+ return text === '' ? 'unknown error' : text
72
+ }
73
+
74
+ /** @param {unknown} value @returns {Date} */
75
+ function resolveNow(value) {
76
+ if (value instanceof Date && Number.isFinite(value.getTime())) return value
77
+ if (typeof value === 'number' && Number.isFinite(value)) return new Date(value)
78
+ if (typeof value === 'string' && value !== '') {
79
+ const time = Date.parse(value)
80
+ if (!Number.isNaN(time)) return new Date(time)
81
+ }
82
+ return new Date()
83
+ }
84
+
85
+ /**
86
+ * Whether a raw YAML scalar value is a !!js expression (or any custom tag)
87
+ * rather than a plain boolean: such a row must never be rewritten.
88
+ * @param {unknown} value
89
+ * @returns {boolean}
90
+ */
91
+ export function isExpression(value) {
92
+ if (typeof value !== 'string') return false
93
+ const trimmed = value.trim()
94
+ return trimmed.startsWith('!')
95
+ }
96
+
97
+ /** Strip a trailing plain-scalar comment (" #...") without touching quoted text. */
98
+ function stripPlainComment(value) {
99
+ const index = value.search(/[ \t]#/)
100
+ return index < 0 ? value : value.slice(0, index)
101
+ }
102
+
103
+ /**
104
+ * Parse one id value written after "- id:". Returns the id or null when the
105
+ * value cannot be safely recognised (tag/expression, malformed quoting, ...).
106
+ * @param {string} raw
107
+ * @returns {string | null}
108
+ */
109
+ function parseEntryIdValue(raw) {
110
+ const value = raw.trim()
111
+ if (value === '' || value.startsWith('!')) return null
112
+ if (value.startsWith('"')) {
113
+ const match = /^"((?:[^"\\]|\\.)*)"/.exec(value)
114
+ if (match === null) return null
115
+ try {
116
+ const parsed = JSON.parse(match[0])
117
+ return typeof parsed === 'string' && parsed !== '' ? parsed : null
118
+ } catch {
119
+ return null
120
+ }
121
+ }
122
+ if (value.startsWith("'")) {
123
+ const match = /^'((?:[^']|'')*)'/.exec(value)
124
+ if (match === null) return null
125
+ const parsed = match[1].replace(/''/g, "'")
126
+ return parsed === '' ? null : parsed
127
+ }
128
+ const plain = stripPlainComment(value).trim()
129
+ if (plain === '' || /[\s{}\[\],&*?|>]/.test(plain)) return null
130
+ return SAFE_ENTRY_ID.test(plain) ? plain : null
131
+ }
132
+
133
+ /** Classify a disabled property's raw value. @param {string} raw */
134
+ function classifyDisabled(raw) {
135
+ const trimmed = raw.trim()
136
+ if (trimmed === '') return 'null'
137
+ if (trimmed.startsWith('!')) return 'expression'
138
+ const value = stripPlainComment(trimmed).trim()
139
+ if (value === 'true') return 'true'
140
+ if (value === 'false') return 'false'
141
+ if (value === 'null' || value === '~') return 'null'
142
+ return 'other'
143
+ }
144
+
145
+ /** Current boolean-ish value of a disabled line, or null when absent/unknown. */
146
+ function disabledValueOf(kind) {
147
+ if (kind === 'true') return true
148
+ if (kind === 'false') return false
149
+ return null
150
+ }
151
+
152
+ /** Leading whitespace of one line ('' when not indented). */
153
+ function indentOf(line) {
154
+ const match = /^[ \t]*/.exec(line)
155
+ return match === null ? '' : match[0]
156
+ }
157
+
158
+ /**
159
+ * Parse a patch document into top-level blocks.
160
+ *
161
+ * A block is one top-level sequence item. Only blocks opened with
162
+ * "- id: <plain id>" are manageable targets; "- insert:" blocks and their
163
+ * nested rows are recognised and skipped. A top-level id line whose value
164
+ * cannot be safely recognised is reported in `unrecognized` so callers can
165
+ * refuse to append a duplicate row.
166
+ *
167
+ * @param {unknown} content
168
+ * @returns {{
169
+ * eol: string,
170
+ * lines: string[],
171
+ * blocks: object[],
172
+ * unrecognized: { line: number, text: string }[],
173
+ * blocked: 'unrecognized' | null,
174
+ * }}
175
+ */
176
+ export function parsePatchBlocks(content) {
177
+ const text = textOf(content)
178
+ const eol = text.includes('\r\n') ? '\r\n' : '\n'
179
+ const lines = text.split(/\r\n|\n/)
180
+ const blocks = []
181
+ const unrecognized = []
182
+ const isTopLevel = (line) => TOP_LEVEL_ITEM.test(line)
183
+
184
+ let index = 0
185
+ while (index < lines.length) {
186
+ const line = lines[index]
187
+ if (!isTopLevel(line)) {
188
+ index += 1
189
+ continue
190
+ }
191
+ const headerLine = index
192
+ let endLine = index
193
+ let cursor = index + 1
194
+ while (cursor < lines.length) {
195
+ const next = lines[cursor]
196
+ if (next.trim() === '') {
197
+ cursor += 1
198
+ continue
199
+ }
200
+ if (isTopLevel(next) || !/^[ \t]/.test(next)) break
201
+ cursor += 1
202
+ endLine = cursor - 1
203
+ }
204
+ endLine = Math.max(endLine, headerLine)
205
+ index = cursor
206
+
207
+ const keyMatch = ITEM_KEY.exec(line)
208
+ const idLike = new RegExp('^-([ \t]+|)id([ \t]*[:\\s]|$)').test(line)
209
+ if (keyMatch === null) {
210
+ if (idLike) unrecognized.push({ line: headerLine, text: line })
211
+ continue
212
+ }
213
+ const key = keyMatch[2]
214
+ const rest = keyMatch[4]
215
+ if (key === 'insert') {
216
+ blocks.push({ key, insert: true, recognized: false, entryId: '', startLine: headerLine, endLine })
217
+ continue
218
+ }
219
+ if (key !== 'id') continue
220
+ // YAML needs a separator after the colon; "- id:foo" is a scalar, not a row.
221
+ if (rest !== '' && !/^[ \t]/.test(rest)) {
222
+ unrecognized.push({ line: headerLine, text: line })
223
+ continue
224
+ }
225
+ const entryId = parseEntryIdValue(rest)
226
+ if (entryId === null) {
227
+ unrecognized.push({ line: headerLine, text: line })
228
+ continue
229
+ }
230
+
231
+ let firstChildIndent = ''
232
+ let disabledLine = null
233
+ let disabledKind = null
234
+ let disabledComment = ''
235
+ for (let cursor2 = headerLine + 1; cursor2 <= endLine; cursor2 += 1) {
236
+ const child = lines[cursor2]
237
+ if (child.trim() === '') continue
238
+ const property = PROPERTY_LINE.exec(child)
239
+ if (property === null) continue
240
+ const indent = property[1]
241
+ if (firstChildIndent === '') firstChildIndent = indent
242
+ if (indent !== firstChildIndent) continue
243
+ if (property[2] === 'disabled' && disabledLine === null) {
244
+ disabledLine = cursor2
245
+ disabledKind = classifyDisabled(property[3])
246
+ if (disabledKind !== 'expression') {
247
+ const commentIndex = property[3].search(/[ \t]#/)
248
+ if (commentIndex >= 0) disabledComment = property[3].slice(commentIndex).trim()
249
+ }
250
+ }
251
+ }
252
+
253
+ blocks.push({
254
+ key,
255
+ insert: false,
256
+ recognized: true,
257
+ entryId,
258
+ startLine: headerLine,
259
+ endLine,
260
+ firstChildIndent: firstChildIndent === '' ? ' ' : firstChildIndent,
261
+ disabledLine,
262
+ disabledKind,
263
+ disabledComment,
264
+ })
265
+ }
266
+
267
+ // Duplicate top-level rows for one entry id would make a surgical edit
268
+ // ambiguous (a later row silently overrides an earlier one): report them so
269
+ // callers refuse the write instead of guessing.
270
+ const entryCounts = new Map()
271
+ for (const block of blocks) {
272
+ if (!block.recognized) continue
273
+ entryCounts.set(block.entryId, (entryCounts.get(block.entryId) ?? 0) + 1)
274
+ }
275
+ const duplicates = [...entryCounts.entries()].filter(([, count]) => count > 1).map(([entryId]) => entryId)
276
+
277
+ return {
278
+ eol,
279
+ lines,
280
+ blocks,
281
+ unrecognized,
282
+ duplicates,
283
+ blocked: unrecognized.length > 0 ? 'unrecognized' : null,
284
+ }
285
+ }
286
+
287
+ /** Normalize the requested changes into [{entryId, disabled}], last one wins. */
288
+ function normalizeChanges(changes) {
289
+ const list = []
290
+ const index = new Map()
291
+ const add = (entryId, disabled) => {
292
+ if (typeof entryId !== 'string' || entryId.trim() === '') return
293
+ if (typeof disabled !== 'boolean') return
294
+ if (index.has(entryId)) {
295
+ list[index.get(entryId)] = { entryId, disabled }
296
+ return
297
+ }
298
+ index.set(entryId, list.length)
299
+ list.push({ entryId, disabled })
300
+ }
301
+ if (Array.isArray(changes)) {
302
+ for (const change of changes) {
303
+ if (isRecord(change)) add(change.entryId, change.disabled)
304
+ }
305
+ } else if (isRecord(changes)) {
306
+ add(changes.entryId, changes.disabled)
307
+ }
308
+ return list
309
+ }
310
+
311
+ /**
312
+ * Classify a patch document's body:
313
+ * - 'content': a real sequence or arbitrary config that must be edited in place;
314
+ * - 'placeholder': only `[]` (plus comments/blank lines) - replaced by rows;
315
+ * - 'empty': only comments/blank lines - rows are appended.
316
+ * @param {string[]} lines
317
+ * @returns {'content' | 'placeholder' | 'empty'}
318
+ */
319
+ function classifyBody(lines) {
320
+ let sawPlaceholder = false
321
+ for (const line of lines) {
322
+ const trimmed = line.trim()
323
+ if (trimmed === '' || trimmed.startsWith('#')) continue
324
+ if (trimmed === '[]') {
325
+ sawPlaceholder = true
326
+ continue
327
+ }
328
+ return 'content'
329
+ }
330
+ return sawPlaceholder ? 'placeholder' : 'empty'
331
+ }
332
+
333
+ /** Format an entry id as a safe YAML plain scalar (quoted when needed). */
334
+ function formatEntryId(entryId) {
335
+ return SAFE_ENTRY_ID.test(entryId) ? entryId : JSON.stringify(entryId)
336
+ }
337
+
338
+ /** Apply bottom-up line edits: {replace: index, text} or {insertAfter, texts}. */
339
+ function applyLineEdits(lines, edits) {
340
+ const sorted = [...edits].sort((left, right) => {
341
+ const leftAt = left.replace !== undefined ? left.replace : left.insertAfter
342
+ const rightAt = right.replace !== undefined ? right.replace : right.insertAfter
343
+ return rightAt - leftAt
344
+ })
345
+ for (const edit of sorted) {
346
+ if (edit.replace !== undefined) lines[edit.replace] = edit.text
347
+ else lines.splice(edit.insertAfter + 1, 0, ...edit.texts)
348
+ }
349
+ return lines
350
+ }
351
+
352
+ /**
353
+ * Surgically apply one or more disabled toggles to a patch document.
354
+ *
355
+ * @param {unknown} content current file text ('' when the file is absent)
356
+ * @param {Array<{entryId: string, disabled: boolean}> | {entryId: string, disabled: boolean}} changes
357
+ * @returns {{
358
+ * ok: true,
359
+ * content: string,
360
+ * changed: boolean,
361
+ * applied: { entryId: string, disabled: boolean, changed: boolean }[],
362
+ * } | { ok: false, blocked: 'expression' | 'unrecognized', entryId?: string, message: string }}
363
+ */
364
+ export function editPatchContent(content, changes) {
365
+ const source = textOf(content)
366
+ const requested = normalizeChanges(changes)
367
+ if (requested.length === 0) {
368
+ return { ok: true, content: source, changed: false, applied: [] }
369
+ }
370
+ const parsed = parsePatchBlocks(source)
371
+ if (parsed.duplicates.length > 0) {
372
+ return {
373
+ ok: false,
374
+ blocked: 'unrecognized',
375
+ entryId: parsed.duplicates[0],
376
+ message:
377
+ '补丁文件中存在重复的插件行(' + parsed.duplicates[0] + '),无法安全定位要修改的行,已拒绝写入',
378
+ }
379
+ }
380
+ const findBlock = (entryId) => parsed.blocks.find((block) => block.recognized && block.entryId === entryId)
381
+
382
+ for (const change of requested) {
383
+ const block = findBlock(change.entryId)
384
+ if (block !== undefined && block.disabledKind === 'expression') {
385
+ return {
386
+ ok: false,
387
+ blocked: 'expression',
388
+ entryId: change.entryId,
389
+ message: '插件 ' + change.entryId + ' 的休眠开关由 !!js 表达式控制,已拒绝改写',
390
+ }
391
+ }
392
+ }
393
+
394
+ const mode = classifyBody(parsed.lines)
395
+ const missing = requested.filter((change) => findBlock(change.entryId) === undefined)
396
+ if (mode === 'content' && missing.length > 0 && parsed.blocked === 'unrecognized') {
397
+ return {
398
+ ok: false,
399
+ blocked: 'unrecognized',
400
+ entryId: missing[0].entryId,
401
+ message: '补丁文件中存在无法安全识别的插件行,已拒绝追加重复行',
402
+ }
403
+ }
404
+
405
+ const applied = []
406
+ const edits = []
407
+ if (mode === 'content') {
408
+ for (const change of requested) {
409
+ const block = findBlock(change.entryId)
410
+ if (block === undefined) {
411
+ applied.push({ entryId: change.entryId, disabled: change.disabled, changed: true, added: true })
412
+ continue
413
+ }
414
+ if (disabledValueOf(block.disabledKind) === change.disabled) {
415
+ applied.push({ entryId: change.entryId, disabled: change.disabled, changed: false })
416
+ continue
417
+ }
418
+ if (block.disabledLine !== null) {
419
+ const suffix = block.disabledComment === '' ? '' : ' ' + block.disabledComment
420
+ edits.push({
421
+ replace: block.disabledLine,
422
+ text: indentOf(parsed.lines[block.disabledLine]) + 'disabled: ' + String(change.disabled) + suffix,
423
+ })
424
+ } else {
425
+ edits.push({
426
+ insertAfter: block.startLine,
427
+ texts: [block.firstChildIndent + 'disabled: ' + String(change.disabled)],
428
+ })
429
+ }
430
+ applied.push({ entryId: change.entryId, disabled: change.disabled, changed: true })
431
+ }
432
+ } else {
433
+ for (const change of requested) {
434
+ applied.push({ entryId: change.entryId, disabled: change.disabled, changed: true, added: true })
435
+ }
436
+ }
437
+
438
+ const lines = mode === 'content' ? [...parsed.lines] : parsed.lines.filter((line) => !(mode === 'placeholder' && line.trim() === '[]'))
439
+ applyLineEdits(lines, edits)
440
+
441
+ const additions = applied.filter((row) => row.added === true)
442
+ if (additions.length > 0) {
443
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop()
444
+ for (const addition of additions) {
445
+ lines.push('- id: ' + formatEntryId(addition.entryId))
446
+ lines.push(' disabled: ' + String(addition.disabled))
447
+ }
448
+ }
449
+
450
+ const next = lines.join(parsed.eol)
451
+ const endsWithEol = /(?:\r\n|\n)$/.test(next)
452
+ const output = endsWithEol || next === '' ? (next === '' ? '' : next) : next + parsed.eol
453
+ return {
454
+ ok: true,
455
+ content: output,
456
+ changed: applied.some((row) => row.changed === true),
457
+ applied,
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Convenience wrapper for one row: set disabled on a single entry id.
463
+ * @param {unknown} content @param {string} entryId @param {boolean} disabled
464
+ * @returns {ReturnType<typeof editPatchContent>}
465
+ */
466
+ export function setSingleRowDisabled(content, entryId, disabled) {
467
+ return editPatchContent(content, [{ entryId, disabled }])
468
+ }
469
+
470
+ /** Content for a freshly created patch file: a valid empty YAML sequence. */
471
+ export function initialPatchContent() {
472
+ return EMPTY_SEQUENCE
473
+ }
474
+
475
+ /**
476
+ * Validate patch YAML with yaml.parseDocument before any byte is written.
477
+ * `!!js/*` tags on unrelated rows land in doc.warnings (TAG_RESOLVE_FAILED) and
478
+ * are allowed; doc.errors or a non-sequence top level refuse the write.
479
+ * @param {unknown} content
480
+ * @returns {{ ok: true, document: object, warnings: string[] }}
481
+ * @throws {Error & { code: 'PATCH_YAML_INVALID' }}
482
+ */
483
+ export function validatePatchYaml(content) {
484
+ const text = textOf(content)
485
+ const document = parseDocument(text)
486
+ if (document.errors.length > 0) {
487
+ const first = String(document.errors[0]?.message ?? 'unknown YAML error')
488
+ const error = new Error('补丁 YAML 校验失败:' + first.split('\n')[0])
489
+ error.code = 'PATCH_YAML_INVALID'
490
+ error.details = document.errors.map((item) => String(item.code ?? 'YAML_ERROR'))
491
+ throw error
492
+ }
493
+ if (!isSeq(document.contents)) {
494
+ const error = new Error('补丁 YAML 顶层必须是数组序列,已拒绝写入')
495
+ error.code = 'PATCH_YAML_INVALID'
496
+ throw error
497
+ }
498
+ return {
499
+ ok: true,
500
+ document,
501
+ warnings: document.warnings.map((item) => String(item.code ?? 'YAML_WARNING')),
502
+ }
503
+ }
504
+
505
+ /** Normalize one change row recorded inside a snapshot. */
506
+ function normalizeSnapshotChange(change) {
507
+ if (!isRecord(change)) return { entryId: '', disabled: null, changed: false }
508
+ const row = {
509
+ entryId: typeof change.entryId === 'string' ? change.entryId : '',
510
+ disabled: typeof change.disabled === 'boolean' ? change.disabled : null,
511
+ changed: change.changed !== false,
512
+ }
513
+ if (typeof change.name === 'string' && change.name !== '') row.name = change.name
514
+ return row
515
+ }
516
+
517
+ /**
518
+ * Create the snapshot-backed patch store.
519
+ *
520
+ * Snapshots live in <backupDir>/snapshots/<id>.json and record
521
+ * { existedBefore, previousContent, changes, summary, restored }, so a restore
522
+ * can recreate the exact pre-operation bytes (or delete a patch file this
523
+ * plugin created) and a repeated restore is idempotent. Only the newest
524
+ * 20 snapshots are kept. Writes go through a .tmp file + rename with a copy
525
+ * fallback for Windows EPERM/EXDEV/EEXIST.
526
+ *
527
+ * @param {{ backupDir?: string, io?: Record<string, Function> }} [input]
528
+ * @returns {{
529
+ * snapshotsDir: string,
530
+ * readPatch: (patchPath: string) => Promise<{ existed: boolean, content: string, error: string | null }>,
531
+ * isWritable: (patchPath: string) => Promise<boolean>,
532
+ * writePatch: (input: object) => Promise<string>,
533
+ * listSnapshots: () => Promise<object[]>,
534
+ * latestSnapshot: () => Promise<object | null>,
535
+ * getSnapshot: (id: string) => Promise<object | null>,
536
+ * restoreSnapshot: (snapshotId?: string) => Promise<object>,
537
+ * pruneSnapshots: () => Promise<void>,
538
+ * }}
539
+ */
540
+ export function createPatchStore(input = {}) {
541
+ const settings = isRecord(input) ? input : {}
542
+ const backupDir = typeof settings.backupDir === 'string' ? settings.backupDir : ''
543
+ const snapshotsDir = backupDir === '' ? '' : join(backupDir, 'snapshots')
544
+ const io = { ...DEFAULT_IO, ...(isRecord(settings.io) ? settings.io : {}) }
545
+
546
+ const snapshotPath = (id) => join(snapshotsDir, id + '.json')
547
+
548
+ /** Write one file atomically: .tmp + rename, copy fallback on Windows errors. */
549
+ const writeFileAtomic = async (target, content) => {
550
+ const tempPath = target + '.tmp-' + randomBytes(4).toString('hex')
551
+ try {
552
+ await io.writeFile(tempPath, content, 'utf8')
553
+ } catch (error) {
554
+ try {
555
+ await io.rm(tempPath, { force: true })
556
+ } catch {
557
+ // Cleanup is best-effort.
558
+ }
559
+ throw error
560
+ }
561
+ try {
562
+ await io.rename(tempPath, target)
563
+ } catch (error) {
564
+ const code = isRecord(error) ? error.code : undefined
565
+ if (code === 'EPERM' || code === 'EXDEV' || code === 'EEXIST' || code === 'EACCES') {
566
+ try {
567
+ await io.copyFile(tempPath, target)
568
+ await io.rm(tempPath, { force: true })
569
+ return
570
+ } catch (copyError) {
571
+ try {
572
+ await io.rm(tempPath, { force: true })
573
+ } catch {
574
+ // Cleanup is best-effort.
575
+ }
576
+ throw copyError
577
+ }
578
+ }
579
+ try {
580
+ await io.rm(tempPath, { force: true })
581
+ } catch {
582
+ // Cleanup is best-effort.
583
+ }
584
+ throw error
585
+ }
586
+ }
587
+
588
+ const writeSnapshotFile = async (snapshot) => {
589
+ await writeFileAtomic(snapshotPath(snapshot.id), JSON.stringify(snapshot, null, 2) + '\n')
590
+ }
591
+
592
+ const readSnapshotFile = async (id) => {
593
+ if (snapshotsDir === '' || typeof id !== 'string' || !SNAPSHOT_ID_PATTERN.test(id)) return null
594
+ try {
595
+ const parsed = JSON.parse(await io.readFile(snapshotPath(id), 'utf8'))
596
+ if (!isRecord(parsed) || typeof parsed.id !== 'string' || !SNAPSHOT_ID_PATTERN.test(parsed.id)) return null
597
+ return parsed
598
+ } catch {
599
+ return null
600
+ }
601
+ }
602
+
603
+ /** Read the patch file; a missing file is not an error (existedBefore=false). */
604
+ const readPatch = async (patchPath) => {
605
+ if (typeof patchPath !== 'string' || patchPath === '') return { existed: false, content: '', error: '补丁文件路径不可用' }
606
+ try {
607
+ const content = await io.readFile(patchPath, 'utf8')
608
+ return { existed: true, content: typeof content === 'string' ? content : String(content), error: null }
609
+ } catch (error) {
610
+ const code = isRecord(error) ? error.code : undefined
611
+ if (code === 'ENOENT') return { existed: false, content: '', error: null }
612
+ return { existed: false, content: '', error: errorText(error) }
613
+ }
614
+ }
615
+
616
+ /** Whether the patch file (or its not-yet-existing directory) is writable. */
617
+ const isWritable = async (patchPath) => {
618
+ if (typeof patchPath !== 'string' || patchPath === '') return false
619
+ try {
620
+ await io.access(patchPath, fsConstants.W_OK)
621
+ return true
622
+ } catch (error) {
623
+ const code = isRecord(error) ? error.code : undefined
624
+ if (code !== 'ENOENT') return false
625
+ }
626
+ try {
627
+ await io.access(dirname(patchPath), fsConstants.W_OK)
628
+ return true
629
+ } catch {
630
+ return false
631
+ }
632
+ }
633
+
634
+ /** All readable snapshots, newest first. */
635
+ const listSnapshots = async () => {
636
+ if (snapshotsDir === '') return []
637
+ let names
638
+ try {
639
+ names = await io.readdir(snapshotsDir)
640
+ } catch {
641
+ return []
642
+ }
643
+ const snapshots = []
644
+ for (const name of Array.isArray(names) ? names : []) {
645
+ if (typeof name !== 'string' || !name.endsWith('.json')) continue
646
+ const id = name.slice(0, -'.json'.length)
647
+ if (!SNAPSHOT_ID_PATTERN.test(id)) continue
648
+ const snapshot = await readSnapshotFile(id)
649
+ if (snapshot !== null) snapshots.push(snapshot)
650
+ }
651
+ snapshots.sort((left, right) => {
652
+ const leftAt = typeof left.createdAt === 'string' ? left.createdAt : ''
653
+ const rightAt = typeof right.createdAt === 'string' ? right.createdAt : ''
654
+ if (leftAt < rightAt) return 1
655
+ if (leftAt > rightAt) return -1
656
+ return 0
657
+ })
658
+ return snapshots
659
+ }
660
+
661
+ /** Newest snapshot that has not been restored yet, or null. */
662
+ const latestSnapshot = async () => {
663
+ const snapshots = await listSnapshots()
664
+ return snapshots.find((snapshot) => snapshot.restored !== true) ?? null
665
+ }
666
+
667
+ const getSnapshot = async (id) => readSnapshotFile(id)
668
+
669
+ /** Keep only the newest MAX_SNAPSHOTS snapshots. */
670
+ const pruneSnapshots = async () => {
671
+ if (snapshotsDir === '') return
672
+ const snapshots = await listSnapshots()
673
+ for (const snapshot of snapshots.slice(MAX_SNAPSHOTS)) {
674
+ try {
675
+ await io.rm(snapshotPath(snapshot.id), { force: true })
676
+ } catch {
677
+ // Pruning is best-effort; an old snapshot staying is harmless.
678
+ }
679
+ }
680
+ }
681
+
682
+ /**
683
+ * Snapshot the current bytes, then write the new patch content atomically.
684
+ * A failed write removes its own snapshot and throws PATCH_WRITE_FAILED.
685
+ * @returns {Promise<string>} snapshot id
686
+ */
687
+ const writePatch = async (input2 = {}) => {
688
+ const patchSettings = isRecord(input2) ? input2 : {}
689
+ const patchPath = typeof patchSettings.patchPath === 'string' ? patchSettings.patchPath : ''
690
+ if (patchPath === '') {
691
+ const error = new Error('补丁文件路径不可用,无法写入')
692
+ error.code = 'PATCH_PATH_MISSING'
693
+ throw error
694
+ }
695
+ if (snapshotsDir === '') {
696
+ const error = new Error('未配置快照目录,已拒绝写入(所有修改必须可撤销)')
697
+ error.code = 'PATCH_SNAPSHOT_UNAVAILABLE'
698
+ throw error
699
+ }
700
+ const nextContent = typeof patchSettings.nextContent === 'string' ? patchSettings.nextContent : ''
701
+ const createdAt = resolveNow(patchSettings.now)
702
+ const snapshot = {
703
+ id: 'snap-' + createdAt.toISOString().replace(/[:.]/g, '-') + '-' + randomBytes(3).toString('hex'),
704
+ createdAt: createdAt.toISOString(),
705
+ patchPath,
706
+ existedBefore: patchSettings.existedBefore === true,
707
+ previousContent: typeof patchSettings.previousContent === 'string' ? patchSettings.previousContent : '',
708
+ changes: Array.isArray(patchSettings.changes) ? patchSettings.changes.map(normalizeSnapshotChange) : [],
709
+ summary:
710
+ typeof patchSettings.summary === 'string' && patchSettings.summary !== '' ? patchSettings.summary : '修改补丁配置',
711
+ restored: false,
712
+ }
713
+ if (snapshotsDir !== '') {
714
+ try {
715
+ await io.mkdir(snapshotsDir, { recursive: true })
716
+ await writeSnapshotFile(snapshot)
717
+ } catch (error) {
718
+ const failure = new Error('写入操作快照失败:' + errorText(error))
719
+ failure.code = 'PATCH_WRITE_FAILED'
720
+ throw failure
721
+ }
722
+ }
723
+ try {
724
+ await io.mkdir(dirname(patchPath), { recursive: true })
725
+ await writeFileAtomic(patchPath, nextContent)
726
+ } catch (error) {
727
+ if (snapshotsDir !== '') {
728
+ try {
729
+ await io.rm(snapshotPath(snapshot.id), { force: true })
730
+ } catch {
731
+ // Cleanup is best-effort.
732
+ }
733
+ }
734
+ const failure = new Error('写入补丁文件失败:' + errorText(error))
735
+ failure.code = 'PATCH_WRITE_FAILED'
736
+ throw failure
737
+ }
738
+ await pruneSnapshots()
739
+ return snapshot.id
740
+ }
741
+
742
+ /**
743
+ * Restore one snapshot (explicit id or the latest unrestored one).
744
+ * Idempotent: restoring an already-restored snapshot reports
745
+ * alreadyRestored=true without touching the file again. When the patch file
746
+ * did not exist before the operation, the created file is deleted.
747
+ * @param {string} [snapshotId]
748
+ * @returns {Promise<object>}
749
+ */
750
+ const restoreSnapshot = async (snapshotId) => {
751
+ let snapshot
752
+ if (snapshotId !== undefined && snapshotId !== null) {
753
+ if (typeof snapshotId !== 'string' || !SNAPSHOT_ID_PATTERN.test(snapshotId)) return { error: 'invalid-id' }
754
+ snapshot = await readSnapshotFile(snapshotId)
755
+ if (snapshot === null) return { error: 'not-found' }
756
+ } else {
757
+ snapshot = await latestSnapshot()
758
+ if (snapshot === null) return { snapshot: null, restored: false, alreadyRestored: false }
759
+ }
760
+ if (snapshot.restored === true) return { snapshot, restored: true, alreadyRestored: true }
761
+ try {
762
+ if (snapshot.existedBefore === true) {
763
+ await io.mkdir(dirname(snapshot.patchPath), { recursive: true })
764
+ await writeFileAtomic(snapshot.patchPath, typeof snapshot.previousContent === 'string' ? snapshot.previousContent : '')
765
+ } else {
766
+ await io.rm(snapshot.patchPath, { force: true })
767
+ }
768
+ } catch (error) {
769
+ const failure = new Error('恢复补丁文件失败:' + errorText(error))
770
+ failure.code = 'PATCH_WRITE_FAILED'
771
+ throw failure
772
+ }
773
+ snapshot.restored = true
774
+ snapshot.restoredAt = new Date().toISOString()
775
+ if (snapshotsDir !== '') {
776
+ try {
777
+ await writeSnapshotFile(snapshot)
778
+ } catch {
779
+ // The file restore already succeeded; a stale flag only repeats a no-op restore.
780
+ }
781
+ }
782
+ return { snapshot, restored: true, alreadyRestored: false }
783
+ }
784
+
785
+ return {
786
+ snapshotsDir,
787
+ readPatch,
788
+ isWritable,
789
+ writePatch,
790
+ listSnapshots,
791
+ latestSnapshot,
792
+ getSnapshot,
793
+ restoreSnapshot,
794
+ pruneSnapshots,
795
+ }
796
+ }
797
+