dsh-zipfix 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1228 @@
1
+ /**
2
+ * 修复操作核心(对应交接文档 §5 方法论与 §6.5 ALG-3 ~ ALG-7)。
3
+ *
4
+ * 所有会落盘的操作都遵守三条安全红线:
5
+ * 1. 永不删除、永不覆盖源 ZIP / 源文件;
6
+ * 2. 改名前后记录 size(可选再加 SHA-256)并复核;
7
+ * 3. 目标同名时自动加 `_fixed` 序号后缀,绝不静默覆盖。
8
+ */
9
+
10
+ import fsp from 'node:fs/promises';
11
+ import path from 'node:path';
12
+ import {
13
+ crc32,
14
+ extractEntry,
15
+ fileCrc32,
16
+ formatCrc,
17
+ openZipCatalog,
18
+ verifyFixedZip,
19
+ writeFixedZip,
20
+ } from './zip.js';
21
+ import {
22
+ classifyName,
23
+ detectRedundantRoot,
24
+ sanitizeEntryName,
25
+ sanitizePathSegment,
26
+ sniffZipEncoding,
27
+ summarizeForms,
28
+ suspicionMarkers,
29
+ tryReverseName,
30
+ } from './detect.js';
31
+ import { decodeUtf8Replacement, encodeText, hasFffd, countFffd } from './encoding.js';
32
+ import { buildReport, writeReportFiles } from './report.js';
33
+
34
+ /* ------------------------------------------------------------------ *
35
+ * 通用小工具
36
+ * ------------------------------------------------------------------ */
37
+
38
+ function throwIfAborted(signal) {
39
+ if (signal?.aborted) throw new DOMException('操作已取消', 'AbortError');
40
+ }
41
+
42
+ async function pathExists(target) {
43
+ try {
44
+ await fsp.lstat(target);
45
+ return true;
46
+ } catch (error) {
47
+ if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return false;
48
+ throw error;
49
+ }
50
+ }
51
+
52
+ async function isDirectory(target) {
53
+ try {
54
+ return (await fsp.stat(target)).isDirectory();
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+
60
+ function splitName(name) {
61
+ const isDir = name.endsWith('/');
62
+ const body = isDir ? name.slice(0, -1) : name;
63
+ const slash = body.lastIndexOf('/');
64
+ const dirPart = slash >= 0 ? body.slice(0, slash + 1) : '';
65
+ const file = slash >= 0 ? body.slice(slash + 1) : body;
66
+ const dot = file.lastIndexOf('.');
67
+ const stem = dot > 0 ? file.slice(0, dot) : file;
68
+ const ext = dot > 0 ? file.slice(dot) : '';
69
+ return { dirPart, stem, ext, isDir };
70
+ }
71
+
72
+ /** 在名字主干后追加后缀(保留扩展名与目录部分;目录保留末尾 '/')。 */
73
+ function addSuffix(name, suffix) {
74
+ const { dirPart, stem, ext, isDir } = splitName(name);
75
+ return isDir ? `${dirPart}${stem}${suffix}/` : `${dirPart}${stem}${suffix}${ext}`;
76
+ }
77
+
78
+ /** 多级相对路径的冲突处理(用于解压落盘;目录允许合并)。 */
79
+ async function uniqueNestedPath(root, relative, { suffix = '_fixed' } = {}) {
80
+ const { dirPart, stem, ext, isDir } = splitName(relative);
81
+ let name = isDir ? `${dirPart}${stem}` : `${dirPart}${stem}${ext}`;
82
+ let attempt = 1;
83
+ while (true) {
84
+ const target = path.join(root, name);
85
+ const exists = await pathExists(target);
86
+ if (!exists) return { relative: isDir ? `${name}/` : name, target, existingDirectory: false };
87
+ if (isDir && (await isDirectory(target))) return { relative: `${name}/`, target, existingDirectory: true };
88
+ attempt++;
89
+ if (attempt > 1000) throw new Error(`无法为 ${relative} 找到不冲突的名字`);
90
+ const tag = attempt === 2 ? suffix : `${suffix}_${attempt - 1}`;
91
+ name = `${dirPart}${stem}${tag}${isDir ? '' : ext}`;
92
+ }
93
+ }
94
+ async function uniqueTargetPath(dir, desiredSegment, { isDir = false, suffix = '_fixed' } = {}) {
95
+ let candidate = desiredSegment;
96
+ let attempt = 1;
97
+ while (true) {
98
+ const target = path.join(dir, candidate);
99
+ const exists = await pathExists(target);
100
+ if (!exists) return { name: candidate, target, existingDirectory: false };
101
+ if (isDir && (await isDirectory(target))) return { name: candidate, target, existingDirectory: true };
102
+ attempt++;
103
+ if (attempt > 1000) throw new Error(`无法为 ${desiredSegment} 找到不冲突的名字`);
104
+ const tag = attempt === 2 ? suffix : `${suffix}_${attempt - 1}`;
105
+ candidate = isDir ? `${desiredSegment}${tag}` : addSuffix(desiredSegment, tag);
106
+ }
107
+ }
108
+
109
+ /** 单个路径段的安全化(用于已解压目录改名)。 */
110
+ export function sanitizeSegment(name) {
111
+ return sanitizePathSegment(name);
112
+ }
113
+
114
+ /** 条目在「读取方未声明编码」时的显示形态,用于报告与人工核对。 */
115
+ export function mojibakeDisplay(entry) {
116
+ if (entry.utf8Flag) {
117
+ try {
118
+ return new TextDecoder('utf-8', { fatal: true }).decode(entry.nameBytes);
119
+ } catch {
120
+ return decodeUtf8Replacement(entry.nameBytes);
121
+ }
122
+ }
123
+ return decodeUtf8Replacement(entry.nameBytes);
124
+ }
125
+
126
+ /* ------------------------------------------------------------------ *
127
+ * 形态 A:已解压目录批量改名(ALG-5)
128
+ * ------------------------------------------------------------------ */
129
+
130
+ /** 审计报告固定写入被处理目录下的这个子目录,避免污染用户文件列表。 */
131
+ export const REPORTS_DIR_NAME = '_zipfix-reports';
132
+ /** 旧版本直接写在目标目录里的报告文件名前缀(扫描/配对时一并跳过)。 */
133
+ const LEGACY_REPORT_FILE = /^zipfix-(?:fix-zip|rename-dir|match-source)-/;
134
+
135
+ /** 报告子目录的绝对路径。 */
136
+ export function reportsDirectory(baseDir) {
137
+ return path.join(baseDir, REPORTS_DIR_NAME);
138
+ }
139
+
140
+ /** 递归收集目录项(自底向上:先深后浅),保证父目录改名时子项已处理完。 */
141
+ async function collectTree(root, { recursive = true } = {}) {
142
+ const files = [];
143
+ const dirs = [];
144
+ async function walk(current, relative) {
145
+ const children = await fsp.readdir(current, { withFileTypes: true });
146
+ for (const child of children) {
147
+ if (child.isDirectory() && child.name === REPORTS_DIR_NAME) continue; // 跳过本插件自己的报告目录
148
+ if (child.isFile() && LEGACY_REPORT_FILE.test(child.name)) continue; // 跳过旧版报告文件
149
+ const abs = path.join(current, child.name);
150
+ const rel = relative === '' ? child.name : `${relative}/${child.name}`;
151
+ if (child.isDirectory()) {
152
+ if (recursive) await walk(abs, rel);
153
+ dirs.push({ abs, rel, name: child.name, depth: rel.split('/').length });
154
+ } else if (child.isFile()) {
155
+ files.push({ abs, rel, name: child.name, depth: rel.split('/').length });
156
+ }
157
+ }
158
+ }
159
+ await walk(root, '');
160
+ // 深度大的先处理;同深度按名字稳定排序,保证报告可复现
161
+ files.sort((a, b) => b.depth - a.depth || a.rel.localeCompare(b.rel));
162
+ dirs.sort((a, b) => b.depth - a.depth || a.rel.localeCompare(b.rel));
163
+ return { files, dirs };
164
+ }
165
+
166
+ /**
167
+ * 用「旧绝对路径 → 新绝对路径」映射把原始路径解析成改名完成后的最终路径。
168
+ * 逐段前进:旧路径用于查映射,新路径用于拼接(改名只改名字,不改父目录层级)。
169
+ * @param {string} root 未被改名的根目录
170
+ * @param {string} originalAbs 改名前的绝对路径
171
+ * @param {Map<string, string>} renameMap 旧绝对路径 → 改名目标绝对路径
172
+ * @returns {string} 最终绝对路径
173
+ */
174
+ function resolveFinalPath(root, originalAbs, renameMap) {
175
+ const relative = path.relative(root, originalAbs);
176
+ if (relative === '' || relative.startsWith('..')) return originalAbs;
177
+ let currentOld = root;
178
+ let currentNew = root;
179
+ for (const segment of relative.split(path.sep)) {
180
+ currentOld = path.join(currentOld, segment);
181
+ const mapped = renameMap.get(currentOld);
182
+ currentNew = mapped === undefined ? path.join(currentNew, segment) : path.join(currentNew, path.basename(mapped));
183
+ }
184
+ return currentNew;
185
+ }
186
+
187
+ /**
188
+ * 对已解压目录做形态 A 批量改名(cp437/latin-1 → GBK)。
189
+ * @param {object} options
190
+ * @param {string} options.root 目录绝对路径
191
+ * @param {boolean} [options.dryRun] 默认 true:只出计划不动文件
192
+ * @param {boolean} [options.recursive] 默认 true
193
+ * @param {boolean} [options.verifyHashes] 是否计算 SHA-256(默认 false,仅记录 size)
194
+ * @param {AbortSignal} [options.signal]
195
+ * @returns {Promise<object>} 结构化报告
196
+ */
197
+ export async function renameDirectory({ root, dryRun = true, recursive = true, verifyHashes = false, signal }) {
198
+ const startedAt = new Date();
199
+ if (!(await isDirectory(root))) throw new Error(`目录不存在或不是目录:${root}`);
200
+ const { files, dirs } = await collectTree(root, { recursive });
201
+ const candidates = [...files, ...dirs].sort((a, b) => b.depth - a.depth || a.rel.localeCompare(b.rel));
202
+ const rows = [];
203
+ const failures = [];
204
+ const skipped = [];
205
+ let renamed = 0;
206
+
207
+ // 先做计划(必须整体规划完再动手,便于报告与 dry-run)
208
+ const plans = [];
209
+ for (const item of candidates) {
210
+ throwIfAborted(signal);
211
+ const classified = classifyName(item.name);
212
+ if (classified.form === 'irreversible') {
213
+ failures.push({ original: item.rel, reason: `含 ${countFffd(item.name)} 个 U+FFFD,字节已销毁,需找源包或内容反推` });
214
+ continue;
215
+ }
216
+ if (classified.form === 'double') {
217
+ failures.push({ original: item.rel, reason: '二次损坏(锟斤拷型),基本只能靠源包还原' });
218
+ continue;
219
+ }
220
+ if (classified.form === 'A' || classified.form === 'A2') {
221
+ const safeName = sanitizeSegment(classified.fixed);
222
+ plans.push({
223
+ item,
224
+ from: item.name,
225
+ to: safeName,
226
+ basis: `${classified.chain}(形态 ${classified.form})`,
227
+ markers: classified.markers ?? [],
228
+ });
229
+ continue;
230
+ }
231
+ if (classified.form === 'unknown') {
232
+ skipped.push({ original: item.rel, reason: '无法自动识别编码,保持原名' });
233
+ }
234
+ }
235
+
236
+ /** 旧绝对路径 → 改名目标绝对路径(成功改名后记录,用于回填最终路径)。 */
237
+ const renameMap = new Map();
238
+
239
+ if (!dryRun) {
240
+ for (const plan of plans) {
241
+ throwIfAborted(signal);
242
+ const source = plan.item.abs;
243
+ const dir = path.dirname(source);
244
+ let before;
245
+ try {
246
+ before = await fsp.stat(source);
247
+ } catch (error) {
248
+ failures.push({ original: plan.item.rel, reason: `读取源状态失败:${error.message}` });
249
+ continue;
250
+ }
251
+ const isDir = before.isDirectory();
252
+ let resolved;
253
+ try {
254
+ resolved = await uniqueTargetPath(dir, plan.to, { isDir });
255
+ } catch (error) {
256
+ failures.push({ original: plan.item.rel, reason: error.message });
257
+ continue;
258
+ }
259
+ if (resolved.target === source) continue;
260
+ let sha256Before;
261
+ if (verifyHashes && !isDir) {
262
+ try {
263
+ sha256Before = (await fileCrc32(source, { signal })).sha256;
264
+ } catch (error) {
265
+ failures.push({ original: plan.item.rel, reason: `计算 SHA-256 失败:${error.message}` });
266
+ continue;
267
+ }
268
+ }
269
+ try {
270
+ await fsp.rename(source, resolved.target);
271
+ } catch (error) {
272
+ failures.push({ original: plan.item.rel, reason: `改名失败:${error.message}` });
273
+ continue;
274
+ }
275
+ let after;
276
+ try {
277
+ after = await fsp.stat(resolved.target);
278
+ } catch (error) {
279
+ failures.push({ original: plan.item.rel, reason: `改名后复核失败:${error.message}` });
280
+ continue;
281
+ }
282
+ let verify = 'size 一致';
283
+ const noteParts = [];
284
+ if (plan.markers.length > 0) noteParts.push(`可疑痕迹:${plan.markers.join('、')}`);
285
+ if (resolved.existingDirectory) noteParts.push('目标目录已存在,已合并');
286
+ if (verifyHashes && sha256Before) {
287
+ const sha256After = (await fileCrc32(resolved.target, { signal })).sha256;
288
+ if (sha256After !== sha256Before) {
289
+ failures.push({ original: plan.item.rel, reason: '改名后 SHA-256 不一致(已回滚)' });
290
+ await fsp.rename(resolved.target, source).catch(() => {});
291
+ continue;
292
+ }
293
+ verify = 'SHA-256 一致';
294
+ } else if (after.size !== before.size) {
295
+ failures.push({ original: plan.item.rel, reason: '改名后 size 不一致' });
296
+ continue;
297
+ }
298
+ renamed++;
299
+ renameMap.set(source, resolved.target);
300
+ rows.push({
301
+ action: isDir ? '改目录名' : '改文件名',
302
+ original: plan.item.rel,
303
+ abs: source,
304
+ basis: plan.basis,
305
+ verify,
306
+ note: noteParts.join(';'),
307
+ });
308
+ }
309
+ } else {
310
+ for (const plan of plans) {
311
+ let before = null;
312
+ try {
313
+ before = await fsp.stat(plan.item.abs);
314
+ } catch {
315
+ /* dry-run 只做展示,状态读取失败不阻断计划 */
316
+ }
317
+ const isDir = before?.isDirectory() ?? false;
318
+ let resolved = null;
319
+ try {
320
+ resolved = await uniqueTargetPath(path.dirname(plan.item.abs), plan.to, { isDir });
321
+ } catch {
322
+ /* 冲突探测失败时退回未加后缀的计划名 */
323
+ }
324
+ const target = resolved?.target ?? path.join(path.dirname(plan.item.abs), plan.to);
325
+ renameMap.set(plan.item.abs, target);
326
+ rows.push({
327
+ action: resolved?.existingDirectory ? '改名(目标目录已存在,将合并)' : '改名(计划)',
328
+ original: plan.item.rel,
329
+ abs: plan.item.abs,
330
+ basis: plan.basis,
331
+ verify: 'dry-run 未执行',
332
+ note: plan.markers.length > 0 ? `可疑痕迹:${plan.markers.join('、')}` : '',
333
+ });
334
+ }
335
+ }
336
+
337
+ // 统一回填最终路径:嵌套条目在改名当刻父目录仍是乱码名,报告必须给最终结果
338
+ for (const row of rows) {
339
+ row.fixed = path.relative(root, resolveFinalPath(root, row.abs, renameMap)).replace(/\\/g, '/');
340
+ delete row.abs;
341
+ }
342
+
343
+ const stats = {
344
+ scanned: candidates.length,
345
+ planned: plans.length,
346
+ renamed,
347
+ failed: failures.length,
348
+ skipped: skipped.length,
349
+ };
350
+ const generatedAt = startedAt.toISOString();
351
+ const report = buildReport({
352
+ title: 'ZIP 中文文件名修复报告(已解压目录)',
353
+ generatedAt,
354
+ meta: [
355
+ { label: '目录', value: root },
356
+ { label: '模式', value: dryRun ? 'dry-run(只报告,未改动任何文件)' : '执行改名' },
357
+ ],
358
+ summary: [
359
+ { label: '扫描项', value: stats.scanned },
360
+ { label: '可还原(形态 A)', value: stats.planned },
361
+ { label: '已改名', value: stats.renamed },
362
+ { label: '失败', value: stats.failed },
363
+ { label: '无法识别', value: stats.skipped },
364
+ ],
365
+ rows: rows.slice(0, 5000),
366
+ failures,
367
+ notes: [
368
+ '形态 A 无损还原原理:原始字节 = 乱码字符串.encode(cp437 或 latin-1),正确名字 = 原始字节.decode(gbk)。',
369
+ 'U+FFFD 是字节级信息丢失(多对一映射),不存在通用算法;请使用 zipfix_match_source 按 (size, CRC32) 配对源包,或使用 zipfix_verify_names 做内容反推验证。',
370
+ ...(skipped.length > 0 ? [`${skipped.length} 个名字无法自动识别编码,已在下方「失败 / 待人工」中列出原始路径,建议人工确认。`] : []),
371
+ ],
372
+ });
373
+ for (const item of skipped) failures.push({ original: item.original, reason: item.reason });
374
+
375
+ let reportPaths = null;
376
+ if (!dryRun) {
377
+ reportPaths = await writeReportFiles(reportsDirectory(root), 'rename-dir', report);
378
+ }
379
+
380
+ return {
381
+ ok: true,
382
+ kind: 'directory',
383
+ root,
384
+ dryRun,
385
+ stats,
386
+ rows: rows.slice(0, 50),
387
+ failures: failures.slice(0, 50),
388
+ report: reportPaths,
389
+ generatedAt,
390
+ summary: dryRun
391
+ ? `dry-run:扫描 ${stats.scanned} 项,可还原 ${stats.planned} 项,待人工 ${stats.failed + stats.skipped} 项(未改动任何文件)`
392
+ : `已改名 ${stats.renamed} 项,失败 ${stats.failed} 项,无法识别 ${stats.skipped} 项`,
393
+ };
394
+ }
395
+
396
+ /* ------------------------------------------------------------------ *
397
+ * 形态 B 最优解:源包 CRC 配对(ALG-6)
398
+ * ------------------------------------------------------------------ */
399
+
400
+ /** 递归列出目录下所有普通文件。 */
401
+ async function listFiles(root, { recursive = true } = {}) {
402
+ const result = [];
403
+ async function walk(current, relative) {
404
+ const children = await fsp.readdir(current, { withFileTypes: true });
405
+ for (const child of children) {
406
+ if (child.isDirectory() && child.name === REPORTS_DIR_NAME) continue; // 跳过本插件自己的报告目录
407
+ if (child.isFile() && LEGACY_REPORT_FILE.test(child.name)) continue; // 跳过旧版报告文件
408
+ const abs = path.join(current, child.name);
409
+ const rel = relative === '' ? child.name : `${relative}/${child.name}`;
410
+ if (child.isDirectory()) {
411
+ if (recursive) await walk(abs, rel);
412
+ } else if (child.isFile()) {
413
+ result.push({ abs, rel, name: child.name });
414
+ }
415
+ }
416
+ }
417
+ await walk(root, '');
418
+ return result;
419
+ }
420
+
421
+ /**
422
+ * 用源 ZIP 的 (size, CRC32) 精确配对已解压目录中的受损文件并改名。
423
+ * 只有「唯一命中」才改名;0 个或多个命中一律进入待人工清单。
424
+ *
425
+ * @param {object} options
426
+ * @param {string} options.directory 受损目录
427
+ * @param {string} options.sourceZip 源 ZIP
428
+ * @param {string} [options.encoding] 强制源 ZIP 条目名编码
429
+ * @param {boolean} [options.dryRun] 默认 true
430
+ * @param {boolean} [options.recursive] 默认 true
431
+ * @param {AbortSignal} [options.signal]
432
+ * @returns {Promise<object>}
433
+ */
434
+ export async function matchSource({
435
+ directory,
436
+ sourceZip,
437
+ encoding,
438
+ dryRun = true,
439
+ recursive = true,
440
+ signal,
441
+ }) {
442
+ const startedAt = new Date();
443
+ if (!(await isDirectory(directory))) throw new Error(`目录不存在或不是目录:${directory}`);
444
+ let stat;
445
+ try {
446
+ stat = await fsp.stat(sourceZip);
447
+ } catch (error) {
448
+ throw new Error(`源 ZIP 不存在或无法访问:${sourceZip}(${error.code ?? error.message})`);
449
+ }
450
+ if (!stat.isFile()) throw new Error(`源 ZIP 不存在或不是文件:${sourceZip}`);
451
+
452
+ const catalog = openZipCatalog(sourceZip);
453
+ try {
454
+ const sniffed = sniffZipEncoding(catalog.entries, { encoding });
455
+ /** @type {Map<string, Array<{name: string, entry: object}>>} */
456
+ const byContent = new Map();
457
+ for (const { entry, name } of sniffed.names) {
458
+ if (entry.isDirectory) continue;
459
+ const key = `${entry.uncompressedSize}:${formatCrc(entry.crc)}`;
460
+ const bucket = byContent.get(key);
461
+ const item = { name, entry };
462
+ if (bucket === undefined) byContent.set(key, [item]);
463
+ else bucket.push(item);
464
+ }
465
+
466
+ const files = await listFiles(directory, { recursive });
467
+ const rows = [];
468
+ const failures = [];
469
+ const unmatched = [];
470
+ let renamed = 0;
471
+
472
+ for (const file of files) {
473
+ throwIfAborted(signal);
474
+ const local = await fileCrc32(file.abs, { signal });
475
+ const key = `${local.size}:${formatCrc(local.crc)}`;
476
+ const bucket = byContent.get(key) ?? [];
477
+ const display = file.rel;
478
+ if (bucket.length === 0) {
479
+ unmatched.push({ path: display, size: local.size, crc: formatCrc(local.crc) });
480
+ continue;
481
+ }
482
+ if (bucket.length > 1) {
483
+ failures.push({
484
+ original: display,
485
+ reason: `源 ZIP 中有 ${bucket.length} 个条目具有相同 (size, CRC32),不猜名字,请人工确认`,
486
+ });
487
+ continue;
488
+ }
489
+ const hit = bucket[0];
490
+ const sanitized = sanitizeEntryName(hit.name);
491
+ if (!sanitized.safe) {
492
+ failures.push({ original: display, reason: `源条目名不安全(${sanitized.reason}):${hit.name}` });
493
+ continue;
494
+ }
495
+ const baseName = path.posix.basename(sanitized.name);
496
+ if (baseName === file.name) {
497
+ rows.push({
498
+ action: '无需改名',
499
+ original: display,
500
+ fixed: display,
501
+ basis: `(size, CRC32) 唯一命中源条目 ${hit.name}`,
502
+ verify: `SHA-256 ${local.sha256.slice(0, 12)}…`,
503
+ note: '名字已与源条目一致',
504
+ });
505
+ continue;
506
+ }
507
+ let resolved;
508
+ try {
509
+ resolved = await uniqueTargetPath(path.dirname(file.abs), baseName);
510
+ } catch (error) {
511
+ failures.push({ original: display, reason: error.message });
512
+ continue;
513
+ }
514
+ const finalName = resolved.name;
515
+ const target = resolved.target;
516
+ if (!dryRun) {
517
+ try {
518
+ await fsp.rename(file.abs, target);
519
+ } catch (error) {
520
+ failures.push({ original: display, reason: `改名失败:${error.message}` });
521
+ continue;
522
+ }
523
+ const after = await fsp.stat(target);
524
+ if (after.size !== local.size) {
525
+ failures.push({ original: display, reason: '改名后 size 不一致,疑似被外部改动' });
526
+ continue;
527
+ }
528
+ const afterCheck = await fileCrc32(target, { signal });
529
+ if (afterCheck.sha256 !== local.sha256) {
530
+ failures.push({ original: display, reason: '改名后 SHA-256 不一致' });
531
+ continue;
532
+ }
533
+ renamed++;
534
+ }
535
+ rows.push({
536
+ action: dryRun ? '改名(计划)' : '改名',
537
+ original: display,
538
+ fixed: path.join(path.relative(directory, path.dirname(file.abs)), finalName).replace(/\\/g, '/'),
539
+ basis: `(size=${local.size}, CRC32=${formatCrc(local.crc)}) 唯一命中源条目「${hit.name}」`,
540
+ verify: dryRun ? 'dry-run 未执行' : 'SHA-256 一致',
541
+ note: '',
542
+ });
543
+ }
544
+
545
+ for (const item of unmatched) {
546
+ failures.push({
547
+ original: item.path,
548
+ reason: `源 ZIP 中找不到 (size=${item.size}, CRC32=${item.crc}) 的条目,无法配对`,
549
+ });
550
+ }
551
+
552
+ const generatedAt = startedAt.toISOString();
553
+ const report = buildReport({
554
+ title: 'ZIP 中文文件名修复报告(源包 CRC 配对)',
555
+ generatedAt,
556
+ meta: [
557
+ { label: '受损目录', value: directory },
558
+ { label: '源 ZIP', value: sourceZip },
559
+ { label: '源 ZIP 条目名编码', value: `${sniffed.encoding ?? 'ascii'}(${sniffed.method},置信度 ${sniffed.confidence})` },
560
+ { label: '模式', value: dryRun ? 'dry-run(只报告,未改动任何文件)' : '执行改名' },
561
+ ],
562
+ summary: [
563
+ { label: '目录文件数', value: files.length },
564
+ { label: '唯一配对成功', value: rows.filter((row) => row.action !== '无需改名').length },
565
+ { label: '已改名', value: renamed },
566
+ { label: '未配对', value: unmatched.length },
567
+ { label: '待人工', value: failures.length },
568
+ ],
569
+ rows: rows.slice(0, 5000),
570
+ failures,
571
+ notes: [
572
+ '这是形态 B(含 U+FFFD)的最优修复路径:(文件大小, CRC32) 唯一命中源 ZIP 中央目录条目,数学上可证。',
573
+ '改名前后均记录 SHA-256 并复核,内容零改动。',
574
+ ],
575
+ });
576
+ const reportPaths = dryRun ? null : await writeReportFiles(reportsDirectory(directory), 'match-source', report);
577
+
578
+ return {
579
+ ok: true,
580
+ kind: 'directory',
581
+ directory,
582
+ sourceZip,
583
+ sourceEncoding: sniffed.encoding,
584
+ sourceMethod: sniffed.method,
585
+ sourceConfidence: sniffed.confidence,
586
+ dryRun,
587
+ stats: {
588
+ scanned: files.length,
589
+ matched: rows.filter((row) => row.action !== '无需改名').length,
590
+ renamed,
591
+ unmatched: unmatched.length,
592
+ failed: failures.length,
593
+ },
594
+ rows: rows.slice(0, 50),
595
+ failures: failures.slice(0, 50),
596
+ report: reportPaths,
597
+ generatedAt,
598
+ summary: dryRun
599
+ ? `dry-run:扫描 ${files.length} 个文件,唯一配对 ${rows.length} 个,未配对 ${unmatched.length} 个,待人工 ${failures.length} 个(未改动任何文件)`
600
+ : `已改名 ${renamed} 个文件,未配对 ${unmatched.length} 个,待人工 ${failures.length} 个`,
601
+ };
602
+ } finally {
603
+ catalog.close();
604
+ }
605
+ }
606
+
607
+ /* ------------------------------------------------------------------ *
608
+ * ZIP 修复:解压 + 修复版 ZIP(ALG-3 / ALG-4)
609
+ * ------------------------------------------------------------------ */
610
+
611
+ /**
612
+ * 修复一个 ZIP:按正确编码解码条目名,无损解压到同级目录,并可选生成修复版 ZIP。
613
+
614
+ * @param {object} options
615
+ * @param {string} options.zipPath ZIP 绝对路径
616
+ * @param {string} [options.outputDir] 输出目录,默认与 ZIP 同级
617
+ * @param {string} [options.encoding] 强制编码(utf-8/gbk/gb18030/big5)
618
+ * @param {boolean} [options.extract] 默认 true
619
+ * @param {boolean} [options.buildFixedZip] 默认 false:是否额外生成修复版 ZIP
620
+ * @param {boolean} [options.stripRoot] 默认 true:剥离与 ZIP 同名的冗余顶层目录
621
+ * @param {boolean} [options.dryRun] 默认 true
622
+ * @param {AbortSignal} [options.signal]
623
+ * @returns {Promise<object>}
624
+ */
625
+ export async function fixZipArchive({
626
+ zipPath,
627
+ outputDir,
628
+ encoding,
629
+ extract = true,
630
+ buildFixedZip = false,
631
+ stripRoot = true,
632
+ dryRun = true,
633
+ force = false,
634
+ displayName,
635
+ signal,
636
+ }) {
637
+ const startedAt = new Date();
638
+ let stat;
639
+ try {
640
+ stat = await fsp.stat(zipPath);
641
+ } catch (error) {
642
+ throw new Error(`ZIP 不存在或无法访问:${zipPath}(${error.code ?? error.message})`);
643
+ }
644
+ if (!stat.isFile()) throw new Error(`ZIP 不存在或不是文件:${zipPath}`);
645
+ const catalog = openZipCatalog(zipPath);
646
+ try {
647
+ const sniffed = sniffZipEncoding(catalog.entries, { encoding });
648
+ const names = sniffed.names;
649
+ const outDir = outputDir ?? path.dirname(zipPath);
650
+ // 冗余顶层目录按「原始压缩包名」判定:上传到临时目录的 ZIP 也保留原始文件名语义
651
+ const rootPrefix = stripRoot ? detectRedundantRoot(names, displayName ?? zipPath) : '';
652
+
653
+ const decodedForms = names.map((item) => ({ name: item.name, form: classifyName(item.name).form }));
654
+ const forms = summarizeForms(decodedForms);
655
+ const lossy = names.filter((item) => item.lossy).length;
656
+ const irreversible = names
657
+ .filter((item) => hasFffd(item.name))
658
+ .map((item) => ({ name: item.name, fffd: countFffd(item.name), original: mojibakeDisplay(item.entry) }));
659
+
660
+ // 条目计划:
661
+ // - extractName:剥离冗余顶层目录后的落盘相对路径(null 表示该条目只进修复版 ZIP)
662
+ // - fixedName :保持原包结构的修复版 ZIP 条目名(只做安全化与去重)
663
+ const plans = [];
664
+ const failures = [];
665
+ const seenExtract = new Map();
666
+ const seenFixed = new Map();
667
+ const dedupe = (candidate, seen, original, label) => {
668
+ const count = (seen.get(candidate) ?? 0) + 1;
669
+ seen.set(candidate, count);
670
+ if (count === 1) return candidate;
671
+ const renamed = addSuffix(candidate, `_${count}`);
672
+ failures.push({ original, reason: `${label}重复,已改名 ${renamed} 以免覆盖` });
673
+ return renamed;
674
+ };
675
+ for (const { entry, name } of names) {
676
+ throwIfAborted(signal);
677
+ const original = mojibakeDisplay(entry);
678
+ if (!entry.supported) {
679
+ failures.push({ original, reason: entry.encrypted ? '条目已加密,无法解压' : `不支持的压缩方式(method=${entry.method})` });
680
+ continue;
681
+ }
682
+ const sanitizedFixed = sanitizeEntryName(name);
683
+ if (!sanitizedFixed.safe) {
684
+ failures.push({ original, reason: `条目名不安全:${sanitizedFixed.reason}` });
685
+ continue;
686
+ }
687
+ const fixedName = dedupe(sanitizedFixed.name, seenFixed, original, '修复版 ZIP 条目名');
688
+ let extractName = fixedName;
689
+ let skipExtract = false;
690
+ if (rootPrefix !== '' && (fixedName === rootPrefix || fixedName.startsWith(rootPrefix))) {
691
+ extractName = fixedName.slice(rootPrefix.length);
692
+ if (extractName.length === 0) skipExtract = true;
693
+ }
694
+ if (!skipExtract) {
695
+ const sanitizedExtract = sanitizeEntryName(extractName);
696
+ if (!sanitizedExtract.safe) {
697
+ failures.push({ original, reason: `解压路径不安全:${sanitizedExtract.reason}` });
698
+ skipExtract = true;
699
+ } else {
700
+ extractName = dedupe(sanitizedExtract.name, seenExtract, original, '解压目标名');
701
+ }
702
+ }
703
+ plans.push({
704
+ entry,
705
+ original,
706
+ extractName: skipExtract ? null : extractName,
707
+ fixedName,
708
+ lossy: name.includes('\uFFFD'),
709
+ });
710
+ }
711
+
712
+ const status =
713
+ sniffed.method === 'declared-utf8'
714
+ ? 'no-fix-needed'
715
+ : sniffed.method === 'ascii'
716
+ ? 'no-fix-needed'
717
+ : sniffed.encoding === 'utf-8'
718
+ ? 'flag-missing-utf8'
719
+ : sniffed.method === 'undecodable'
720
+ ? 'unknown'
721
+ : irreversible.length > 0
722
+ ? 'mixed'
723
+ : 'reversible';
724
+
725
+ const fileCount = catalog.entries.filter((entry) => !entry.isDirectory).length;
726
+ const dirCount = catalog.entries.filter((entry) => entry.isDirectory).length;
727
+ const entriesSummary = {
728
+ total: catalog.entries.length,
729
+ files: fileCount,
730
+ directories: dirCount,
731
+ nonAscii: sniffed.nonAsciiEntries,
732
+ declaredUtf8: sniffed.declaredUtf8Entries,
733
+ lossy,
734
+ };
735
+
736
+ // 「无需修复」必须做到不产生任何改动(交接文档 T2):除非显式 force,
737
+ // 不建目录、不解压、不写修复版 ZIP、也不写报告文件。
738
+ if (status === 'no-fix-needed' && !force) {
739
+ return {
740
+ ok: true,
741
+ kind: 'zip',
742
+ zipPath,
743
+ zipSize: stat.size,
744
+ outputDir: outDir,
745
+ dryRun,
746
+ encoding: sniffed.encoding,
747
+ method: sniffed.method,
748
+ confidence: sniffed.confidence,
749
+ scores: sniffed.scores,
750
+ status,
751
+ entries: entriesSummary,
752
+ forms,
753
+ stripRoot: rootPrefix,
754
+ applied: {
755
+ extractedFiles: 0,
756
+ extractedDirectories: 0,
757
+ extractionFailures: 0,
758
+ fixedZipPath: null,
759
+ fixedZip: null,
760
+ outputDir: outDir,
761
+ report: null,
762
+ },
763
+ rows: [],
764
+ failures: failures.slice(0, 50),
765
+ irreversible: [],
766
+ warnings: sniffed.warnings.slice(0, 20),
767
+ generatedAt: startedAt.toISOString(),
768
+ summary: `文件名编码已合规(${sniffed.method}),未产生任何改动。`,
769
+ };
770
+ }
771
+
772
+ const applied = {
773
+ extractedFiles: 0,
774
+ extractedDirectories: 0,
775
+ extractionFailures: 0,
776
+ fixedZipPath: null,
777
+ fixedZip: null,
778
+ outputDir: outDir,
779
+ report: null,
780
+ };
781
+ const rows = [];
782
+
783
+ if (!dryRun && extract) {
784
+ await fsp.mkdir(outDir, { recursive: true });
785
+ for (const plan of plans) {
786
+ throwIfAborted(signal);
787
+ if (plan.extractName === null) continue; // 冗余根目录本身:只进修复版 ZIP
788
+ const target = path.join(outDir, plan.extractName);
789
+ if (plan.extractName.endsWith('/')) {
790
+ await fsp.mkdir(target, { recursive: true });
791
+ applied.extractedDirectories++;
792
+ rows.push({
793
+ action: '解压目录',
794
+ original: plan.original,
795
+ fixed: plan.extractName,
796
+ basis: `${sniffed.encoding}${sniffed.method === 'forced' ? '(强制)' : ''}`,
797
+ verify: '已创建',
798
+ note: '',
799
+ });
800
+ continue;
801
+ }
802
+ let resolved;
803
+ try {
804
+ resolved = await uniqueNestedPath(outDir, plan.extractName);
805
+ } catch (error) {
806
+ applied.extractionFailures++;
807
+ failures.push({ original: plan.original, reason: error.message });
808
+ continue;
809
+ }
810
+ const finalName = resolved.relative;
811
+ const finalPath = resolved.target;
812
+ try {
813
+ const result = await extractEntry(catalog, plan.entry, finalPath, { signal });
814
+ applied.extractedFiles++;
815
+ rows.push({
816
+ action: '解压',
817
+ original: plan.original,
818
+ fixed: finalName,
819
+ basis: `${sniffed.encoding}${sniffed.method === 'forced' ? '(强制)' : ''}`,
820
+ verify: `size=${result.size},CRC32=${formatCrc(result.crc)} 一致`,
821
+ note: finalName === plan.extractName ? '' : '目标同名,已加后缀',
822
+ });
823
+ } catch (error) {
824
+ applied.extractionFailures++;
825
+ failures.push({ original: plan.original, reason: `解压失败:${error.message}` });
826
+ }
827
+ }
828
+ } else if (dryRun) {
829
+ for (const plan of plans.slice(0, 5000)) {
830
+ if (plan.extractName === null) continue;
831
+ rows.push({
832
+ action: plan.extractName.endsWith('/') ? '解压目录(计划)' : '解压(计划)',
833
+ original: plan.original,
834
+ fixed: plan.extractName,
835
+ basis: `${sniffed.encoding}${sniffed.method === 'forced' ? '(强制)' : ''}`,
836
+ verify: 'dry-run 未执行',
837
+ note: plan.extractName.endsWith('/') ? '' : '将逐条校验 CRC32',
838
+ });
839
+ }
840
+ if (buildFixedZip) {
841
+ const stem = path.basename(zipPath).replace(/\.zip$/i, '');
842
+ rows.unshift({
843
+ action: '生成修复版 ZIP(计划)',
844
+ original: path.basename(zipPath),
845
+ fixed: `${stem}-文件名已修复.zip`,
846
+ basis: '全部条目置位 UTF-8 标志 0x0800 + UTF-8 文件名',
847
+ verify: 'dry-run 未执行',
848
+ note: '将逐条重新压缩并回读自检',
849
+ });
850
+ }
851
+ }
852
+
853
+ if (!dryRun && buildFixedZip) {
854
+ const stem = path.basename(zipPath).replace(/\.zip$/i, '');
855
+ const desired = `${stem}-文件名已修复.zip`;
856
+ const resolvedDest = await uniqueNestedPath(outDir, desired, { suffix: '_fixed' });
857
+ const destPath = resolvedDest.target;
858
+ const fixedZipName = resolvedDest.relative;
859
+ const totalUncompressed = catalog.entries.reduce((sum, entry) => sum + entry.uncompressedSize, 0);
860
+ try {
861
+ await writeFixedZip({
862
+ sourceCatalog: catalog,
863
+ destPath,
864
+ plans: plans.map((plan) => ({ entry: plan.entry, name: plan.fixedName })),
865
+ signal,
866
+ });
867
+ const verification = await verifyFixedZip(destPath, {
868
+ full: totalUncompressed <= 512 * 1024 * 1024,
869
+ signal,
870
+ });
871
+ applied.fixedZipPath = destPath;
872
+ applied.fixedZip = verification;
873
+ rows.push({
874
+ action: '生成修复版 ZIP',
875
+ original: path.basename(zipPath),
876
+ fixed: fixedZipName,
877
+ basis: '全部条目置位 UTF-8 标志 0x0800 + UTF-8 文件名',
878
+ verify: `回读 ${verification.entries} 条目,UTF-8 标志 ${verification.allUtf8Flag ? '全部置位' : '有缺失'},${verification.fullChecked ? '逐条 CRC32 校验通过' : '结构校验通过(体积较大,跳过全量解压校验)'}`,
879
+ note: '',
880
+ });
881
+ } catch (error) {
882
+ failures.push({ original: `${path.basename(zipPath)} → 修复版 ZIP`, reason: `生成失败:${error.message}` });
883
+ }
884
+ }
885
+
886
+ const generatedAt = startedAt.toISOString();
887
+ const report = buildReport({
888
+ title: 'ZIP 中文文件名修复报告(压缩包)',
889
+ generatedAt,
890
+ meta: [
891
+ { label: 'ZIP', value: zipPath },
892
+ { label: 'ZIP 大小', value: `${stat.size} 字节` },
893
+ { label: '条目名编码', value: `${sniffed.encoding ?? '未知'}(${sniffed.method},置信度 ${sniffed.confidence})` },
894
+ { label: '输出目录', value: outDir },
895
+ { label: '模式', value: dryRun ? 'dry-run(只报告,未改动任何文件)' : '解压/重建' },
896
+ ],
897
+ summary: [
898
+ { label: '条目总数', value: catalog.entries.length },
899
+ { label: '文件 / 目录', value: `${fileCount} / ${dirCount}` },
900
+ { label: '非 ASCII 条目', value: sniffed.nonAsciiEntries },
901
+ { label: '可逆还原', value: forms.reversibleA + forms.reversibleA2 },
902
+ { label: '含 U+FFFD(不可逆)', value: forms.irreversible },
903
+ { label: '剥离冗余顶层目录', value: rootPrefix === '' ? '无' : rootPrefix.slice(0, -1) },
904
+ { label: '判定', value: status },
905
+ ],
906
+ rows: rows.slice(0, 5000),
907
+ failures,
908
+ notes: [
909
+ `编码评分:${Object.entries(sniffed.scores).map(([key, value]) => `${key}=${value}`).join(',') || '(无)'}`,
910
+ '修复版 ZIP 显式置位通用位 bit 11(0x0800)并用 UTF-8 写文件名,Windows 资源管理器 / 7-Zip 无需参数即可正确显示。',
911
+ ...sniffed.warnings,
912
+ ...(irreversible.length > 0
913
+ ? ['检测到 U+FFFD:字节已被替换字符覆盖,压缩包内无法还原。请保留源文件,使用 zipfix_match_source 或 zipfix_verify_names。']
914
+ : []),
915
+ ],
916
+ });
917
+
918
+ if (!dryRun) {
919
+ applied.report = await writeReportFiles(reportsDirectory(outDir), 'fix-zip', report);
920
+ }
921
+
922
+ const forcedNoFix = status === 'no-fix-needed' && force && !dryRun;
923
+ const statusText =
924
+ status === 'no-fix-needed'
925
+ ? forcedNoFix
926
+ ? '文件名编码已合规,已按 force:true 强制处理'
927
+ : '文件名编码已合规,无需修复'
928
+ : status === 'flag-missing-utf8'
929
+ ? '名字本身是 UTF-8,但缺少 0x0800 标志位,重建 ZIP 即可'
930
+ : status === 'unknown'
931
+ ? '无法识别编码,建议指定 encoding 或人工处理'
932
+ : status === 'mixed'
933
+ ? `部分条目可逆还原,另有 ${forms.irreversible} 个条目含 U+FFFD 不可逆`
934
+ : '检测到 GBK/GB18030/Big5 文件名,可无损还原';
935
+
936
+ return {
937
+ ok: true,
938
+ kind: 'zip',
939
+ zipPath,
940
+ zipSize: stat.size,
941
+ outputDir: outDir,
942
+ dryRun,
943
+ encoding: sniffed.encoding,
944
+ method: sniffed.method,
945
+ confidence: sniffed.confidence,
946
+ scores: sniffed.scores,
947
+ status,
948
+ entries: entriesSummary,
949
+ forms,
950
+ stripRoot: rootPrefix,
951
+ applied,
952
+ rows: rows.slice(0, 50),
953
+ failures: failures.slice(0, 50),
954
+ irreversible: irreversible.slice(0, 50),
955
+ warnings: sniffed.warnings.slice(0, 20),
956
+ forced: forcedNoFix,
957
+ generatedAt,
958
+ summary: `${statusText}。${dryRun ? 'dry-run:未改动任何文件。' : `已解压 ${applied.extractedFiles} 个文件 / ${applied.extractedDirectories} 个目录,失败 ${applied.extractionFailures} 个。${applied.fixedZipPath ? '已生成修复版 ZIP。' : ''}`}`,
959
+ };
960
+ } finally {
961
+ catalog.close();
962
+ }
963
+ }
964
+
965
+ /* ------------------------------------------------------------------ *
966
+ * ALG-7:内容反推 + 指纹验证
967
+ * ------------------------------------------------------------------ */
968
+
969
+ /**
970
+ * 编码指纹:候选名按 GBK 编码后再按 UTF-8 替换解码。
971
+ * 与交接文档 verify_candidate 的 Python 实现一致(已实测 U+FFFD 语义相同)。
972
+ * @param {string} candidate 候选正确名字
973
+ * @returns {string} 指纹;候选含 GBK 不可编码字符时抛错
974
+ */
975
+ export function fingerprint(candidate) {
976
+ return decodeUtf8Replacement(encodeText(candidate, 'gbk'));
977
+ }
978
+
979
+ /** 把连续 U+FFFD 折叠成单个,用于宽松比对(不同读取器的替换粒度可能不同)。 */
980
+ export function normalizeFffdRuns(text) {
981
+ return text.replace(/\uFFFD+/g, '\uFFFD');
982
+ }
983
+
984
+ /**
985
+ * 验证一个候选名是否就是「产生当前乱码」的原始名字。
986
+ * @param {string} candidate 候选正确名字
987
+ * @param {string} actualMojibake 当前乱码名字
988
+ * @returns {{candidate: string, match: 'exact'|'normalized'|'none'|'unencodable', fingerprint: string|null}}
989
+ */
990
+ export function verifyCandidateName(candidate, actualMojibake) {
991
+ let fp;
992
+ try {
993
+ fp = fingerprint(candidate);
994
+ } catch (error) {
995
+ return { candidate, match: 'unencodable', fingerprint: null, reason: error.message };
996
+ }
997
+ if (fp === actualMojibake) return { candidate, match: 'exact', fingerprint: fp };
998
+ if (normalizeFffdRuns(fp) === normalizeFffdRuns(actualMojibake)) {
999
+ return { candidate, match: 'normalized', fingerprint: fp };
1000
+ }
1001
+ return { candidate, match: 'none', fingerprint: fp };
1002
+ }
1003
+
1004
+ const XML_ENTITIES = new Map([
1005
+ ['amp', '&'],
1006
+ ['lt', '<'],
1007
+ ['gt', '>'],
1008
+ ['quot', '"'],
1009
+ ['apos', "'"],
1010
+ ]);
1011
+
1012
+ function decodeXmlEntities(text) {
1013
+ return text.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (match, body) => {
1014
+ if (body.startsWith('#x') || body.startsWith('#X')) {
1015
+ const code = Number.parseInt(body.slice(2), 16);
1016
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
1017
+ }
1018
+ if (body.startsWith('#')) {
1019
+ const code = Number.parseInt(body.slice(1), 10);
1020
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
1021
+ }
1022
+ return XML_ENTITIES.get(body) ?? match;
1023
+ });
1024
+ }
1025
+
1026
+ function uniqueNonEmpty(texts) {
1027
+ const seen = new Set();
1028
+ const out = [];
1029
+ for (const raw of texts) {
1030
+ const text = raw.replace(/\s+/g, ' ').trim();
1031
+ if (text.length === 0 || seen.has(text)) continue;
1032
+ seen.add(text);
1033
+ out.push(text);
1034
+ if (out.length >= 30) break;
1035
+ }
1036
+ return out;
1037
+ }
1038
+
1039
+ function extractOoxmlParts(catalog, partPaths) {
1040
+ const results = [];
1041
+ for (const partPath of partPaths) {
1042
+ const entry = catalog.entries.find(
1043
+ (item) => item.nameBytes.toString('latin1') === partPath || item.nameBytes.toString('utf8') === partPath,
1044
+ );
1045
+ if (entry === undefined) continue;
1046
+ try {
1047
+ results.push({ partPath, xml: catalog.readEntryBuffer(entry, { maxBytes: 16 * 1024 * 1024 }).toString('utf8') });
1048
+ } catch {
1049
+ /* 单个部件损坏不影响整体 */
1050
+ }
1051
+ }
1052
+ return results;
1053
+ }
1054
+
1055
+ /**
1056
+ * 从文档内部抽取「标题类」候选文本(ALG-7 Step 1)。
1057
+ * 支持 .docx / .xlsx / .pptx(OOXML)与 .pdf(启发式)。
1058
+ * @param {string} filePath 文件路径
1059
+ * @returns {Promise<{kind: string, titles: string[], sources: string[], warnings: string[]}>}
1060
+ */
1061
+ export async function extractDocumentTitles(filePath) {
1062
+ const stat = await fsp.stat(filePath);
1063
+ if (!stat.isFile()) throw new Error(`不是文件:${filePath}`);
1064
+ const ext = path.extname(filePath).toLowerCase();
1065
+ const warnings = [];
1066
+ const titles = [];
1067
+ const sources = [];
1068
+
1069
+ if (ext === '.pdf') {
1070
+ const handle = await fsp.open(filePath, 'r');
1071
+ try {
1072
+ const buffer = Buffer.alloc(Math.min(stat.size, 262144));
1073
+ await handle.read(buffer, 0, buffer.length, 0);
1074
+ const text = buffer.toString('latin1');
1075
+ const matches = [...text.matchAll(/\/Title\s*\(((?:\\.|[^()\\])*)\)/g)];
1076
+ for (const match of matches.slice(0, 10)) {
1077
+ const value = match[1].replace(/\\([()\\])/g, '$1').trim();
1078
+ if (value.length > 0) {
1079
+ titles.push(value);
1080
+ sources.push('/Info /Title');
1081
+ }
1082
+ }
1083
+ if (titles.length === 0) warnings.push('PDF 未找到 /Title 元数据(可能需要专用解析器)');
1084
+ } finally {
1085
+ await handle.close();
1086
+ }
1087
+ return { kind: 'pdf', titles: uniqueNonEmpty(titles), sources: [...new Set(sources)], warnings };
1088
+ }
1089
+
1090
+ if (ext !== '.docx' && ext !== '.xlsx' && ext !== '.pptx') {
1091
+ throw new Error(`不支持的内容反推格式:${ext || '(无扩展名)'}(支持 .docx/.xlsx/.pptx/.pdf)`);
1092
+ }
1093
+
1094
+ const catalog = openZipCatalog(filePath);
1095
+ try {
1096
+ const appParts = extractOoxmlParts(catalog, ['docProps/app.xml']);
1097
+ for (const { xml } of appParts) {
1098
+ const block = xml.match(/<TitlesOfParts>([\s\S]*?)<\/TitlesOfParts>/);
1099
+ if (block) {
1100
+ const parts = [...block[1].matchAll(/<vt:lpstr>([\s\S]*?)<\/vt:lpstr>/g)].map((m) => decodeXmlEntities(m[1]));
1101
+ for (const part of parts) {
1102
+ titles.push(part);
1103
+ sources.push('docProps/app.xml <TitlesOfParts>');
1104
+ }
1105
+ }
1106
+ }
1107
+ const coreParts = extractOoxmlParts(catalog, ['docProps/core.xml']);
1108
+ for (const { xml } of coreParts) {
1109
+ const title = xml.match(/<dc:title>([\s\S]*?)<\/dc:title>/);
1110
+ if (title) {
1111
+ titles.push(decodeXmlEntities(title[1]));
1112
+ sources.push('docProps/core.xml <dc:title>');
1113
+ }
1114
+ }
1115
+ if (ext === '.docx') {
1116
+ const docParts = extractOoxmlParts(catalog, ['word/document.xml']);
1117
+ for (const { xml } of docParts) {
1118
+ const paragraphs = xml
1119
+ .replace(/<\/w:p>/g, '\n')
1120
+ .split('\n')
1121
+ .map((chunk) => decodeXmlEntities(chunk.replace(/<[^>]+>/g, '')).trim())
1122
+ .filter((text) => text.length > 0);
1123
+ for (const paragraph of paragraphs.slice(0, 40)) {
1124
+ titles.push(paragraph);
1125
+ sources.push('word/document.xml 正文');
1126
+ }
1127
+ }
1128
+ }
1129
+ if (ext === '.xlsx') {
1130
+ const sharedParts = extractOoxmlParts(catalog, ['xl/sharedStrings.xml']);
1131
+ for (const { xml } of sharedParts) {
1132
+ const items = [...xml.matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)]
1133
+ .map((match) => decodeXmlEntities(match[1]))
1134
+ .filter((text) => text.trim().length > 0);
1135
+ for (const item of items.slice(0, 40)) {
1136
+ titles.push(item);
1137
+ sources.push('xl/sharedStrings.xml');
1138
+ }
1139
+ }
1140
+ }
1141
+ if (ext === '.pptx') {
1142
+ const slideParts = catalog.entries
1143
+ .map((entry) => entry.nameBytes.toString('utf8'))
1144
+ .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
1145
+ .slice(0, 10);
1146
+ for (const slide of slideParts) {
1147
+ const parts = extractOoxmlParts(catalog, [slide]);
1148
+ for (const { xml } of parts) {
1149
+ const texts = [...xml.matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((match) => decodeXmlEntities(match[1]));
1150
+ if (texts.length > 0) {
1151
+ titles.push(texts[0]);
1152
+ sources.push(slide);
1153
+ }
1154
+ }
1155
+ }
1156
+ }
1157
+ return {
1158
+ kind: ext.slice(1),
1159
+ titles: uniqueNonEmpty(titles),
1160
+ sources: [...new Set(sources)],
1161
+ warnings,
1162
+ };
1163
+ } finally {
1164
+ catalog.close();
1165
+ }
1166
+ }
1167
+
1168
+ /**
1169
+ * ALG-7:抽取文档标题 → 生成候选名 → 指纹验证。只输出「已验证」或「待确认」,不改名。
1170
+ * @param {object} options
1171
+ * @param {string} options.mojibakeName 当前乱码名字(含 U+FFFD 也可)
1172
+ * @param {string[]} [options.candidates] 显式候选名
1173
+ * @param {string} [options.documentPath] 文档路径(自动抽取标题生成候选)
1174
+ * @returns {Promise<object>}
1175
+ */
1176
+ export async function verifyNames({ mojibakeName, candidates = [], documentPath }) {
1177
+ const extMatch = mojibakeName.match(/(\.[A-Za-z0-9]{1,8})$/);
1178
+ const ext = extMatch ? extMatch[1] : '';
1179
+ const stem = ext ? mojibakeName.slice(0, -ext.length) : mojibakeName;
1180
+ const generated = [];
1181
+ const warnings = [];
1182
+ let extraction;
1183
+
1184
+ if (documentPath) {
1185
+ extraction = await extractDocumentTitles(documentPath);
1186
+ warnings.push(...extraction.warnings);
1187
+ for (const title of extraction.titles) {
1188
+ const sanitized = sanitizeSegment(title);
1189
+ if (sanitized.length === 0) continue;
1190
+ generated.push(`${sanitized}${ext}`);
1191
+ // 常见前缀变体:附件序号 / 书名号 / 去空格
1192
+ generated.push(`${sanitized.replace(/\s+/g, '')}${ext}`);
1193
+ for (const prefix of ['附件1:', '附件2:', '附件1-', '附件2-']) generated.push(`${prefix}${sanitized}${ext}`);
1194
+ if (title.includes('“') || title.includes('”')) {
1195
+ const centered = title.replace(/[“”]/g, '').trim();
1196
+ if (centered !== title) generated.push(`${centered}${ext}`);
1197
+ }
1198
+ }
1199
+ }
1200
+
1201
+ const pool = [...new Set([...candidates, ...generated])].filter((item) => item.trim().length > 0);
1202
+ const results = pool.map((candidate) => verifyCandidateName(candidate, mojibakeName));
1203
+ const verified = results.filter((item) => item.match === 'exact' || item.match === 'normalized');
1204
+ return {
1205
+ ok: true,
1206
+ mojibakeName,
1207
+ mojibakeLength: [...stem].length,
1208
+ fffdCount: countFffd(mojibakeName),
1209
+ extension: ext,
1210
+ document: extraction
1211
+ ? { kind: extraction.kind, titles: extraction.titles.slice(0, 30), sources: extraction.sources, warnings: extraction.warnings }
1212
+ : null,
1213
+ candidates: results,
1214
+ verified,
1215
+ warnings: [
1216
+ ...warnings,
1217
+ ...(verified.length === 0
1218
+ ? ['没有任何候选通过指纹验证:请补充候选名,或改用源包 CRC 配对(zipfix_match_source)。']
1219
+ : []),
1220
+ ],
1221
+ summary:
1222
+ verified.length > 0
1223
+ ? `已验证 ${verified.length} 个候选名与乱码指纹完全吻合(可安全改名)。`
1224
+ : `候选 ${results.length} 个,无一通过指纹验证;不得擅自改名。`,
1225
+ };
1226
+ }
1227
+
1228
+ export { classifyName, tryReverseName, suspicionMarkers, crc32 };