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.
- package/LICENSE +21 -0
- package/README.md +36 -2
- package/client.js +871 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +9 -0
- package/index.js +18 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
- package/plugin/index.js +633 -0
- package/plugin/lib/detect.js +436 -0
- package/plugin/lib/encoding.js +369 -0
- package/plugin/lib/fix.js +1228 -0
- package/plugin/lib/report.js +135 -0
- package/plugin/lib/webapi.js +598 -0
- package/plugin/lib/zip.js +842 -0
- package/plugin/locale/en.json +6 -0
- package/plugin/locale/zh.json +6 -0
- package/ui/index.js +26 -0
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 编码嗅探与形态分类(对应交接文档 ALG-2 与 §5.1 决策树)。
|
|
3
|
+
*
|
|
4
|
+
* 三种输入:
|
|
5
|
+
* - ZIP 条目:手里有**原始文件名字节**,嗅探是「多候选严格解码 + 中文得分排序」;
|
|
6
|
+
* - 已解压目录:手里是**误解码后的字符串**,只能反解(cp437/latin1 → GBK);
|
|
7
|
+
* - 含 U+FFFD 的名字:字节已被替换符覆盖,直接判「不可逆」。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
decodeBytes,
|
|
12
|
+
decodeCp437,
|
|
13
|
+
decodeUtf8Replacement,
|
|
14
|
+
encodeText,
|
|
15
|
+
isAscii,
|
|
16
|
+
looksLikeChineseText,
|
|
17
|
+
cjkRatio,
|
|
18
|
+
countFffd,
|
|
19
|
+
hasFffd,
|
|
20
|
+
normalizeEncoding,
|
|
21
|
+
tryDecode,
|
|
22
|
+
tryEncode,
|
|
23
|
+
DECODE_ENCODINGS,
|
|
24
|
+
} from './encoding.js';
|
|
25
|
+
|
|
26
|
+
/** 编码嗅探的候选顺序(gbk 先于 gb18030,等分时取 gbk)。 */
|
|
27
|
+
export const SNIFF_CANDIDATES = Object.freeze(['utf-8', 'gbk', 'gb18030', 'big5']);
|
|
28
|
+
|
|
29
|
+
/** 形态 A 的反解链:误解码编码 → 目标中文编码。cp437 必须排在 latin-1/cp1252 之前。 */
|
|
30
|
+
export const DIR_REVERSE_CHAINS = Object.freeze([
|
|
31
|
+
{ from: 'cp437', to: 'gbk' },
|
|
32
|
+
{ from: 'cp437', to: 'gb18030' },
|
|
33
|
+
{ from: 'latin-1', to: 'gbk' },
|
|
34
|
+
{ from: 'latin-1', to: 'gb18030' },
|
|
35
|
+
{ from: 'cp1252', to: 'gbk' },
|
|
36
|
+
{ from: 'cp1252', to: 'gb18030' },
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
/** CP437 高位区中「正常文件名几乎不会出现」的字符(字节 0xB0–0xFF),用于可疑度提示。 */
|
|
40
|
+
const CP437_DISTINCTIVE = new Set(
|
|
41
|
+
'░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■',
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 高频汉字集合(约 800 字,出自常用字频率表)。
|
|
46
|
+
*
|
|
47
|
+
* 为什么需要它:交接文档指出「条目少时 gbk 与 big5 仅差几十分」是本算法唯一薄弱点。
|
|
48
|
+
* 纯 Unicode 区段打分无法区分「真中文」与「Big5 误解码出来的生僻字」——
|
|
49
|
+
* 二者都落在 U+4E00–U+9FFF。而自然中文里高频字占比极高,随机生僻字几乎为 0,
|
|
50
|
+
* 因此对高频字额外加分,可在短名单上把区分度拉开一个数量级。
|
|
51
|
+
* 该集合只影响候选排序,不改变「严格解码成功」这一硬条件。
|
|
52
|
+
*/
|
|
53
|
+
const COMMON_HANZI = new Set(
|
|
54
|
+
'的一是不了在人有我他这个们中来上大为和国地到以说时要就出会可也你对生能而子那得于着下自之年过发后作里用道行所然家种事成方多经么去法学如都同现当没动面起看定天分还进好小部其些主样理心她本前开但因只从想实日军者意无力它与长把机十民第公此已工使情明性知全三又关点正业外将两高间由问很最重并物手应战向头文体政美相见被利什二等产或新己制身果加西斯月话合回特代内信表化老给世位次度门任常先海通教儿原东声提立及比员解水名真论处走义各入几口认条平系气题活尔更别打女变四神总何电数安少报才结反受目太量再感建务做接必场件计管期市直德资命山金指克许统区保至队形社便空决治展马科司五基眼书非则听白却界达光放强即像难且权思王象完设式色路记南品住告类求据程北边死张该交规万取拉格望觉术领共确传师观清今切院让识候带导争运笑飞风步改收根干造言联持组每济车亲极林服快办议往元英士证近失转夫令准布始怎呢存未远叫台单影具罗字爱击流备兵连调深商算质团集百需价花党华城石级整府离况亚请技际约示复病息究线似官火断精满支视消越器容照须九增研写称企八功吗包片史委乎查轻易早曾除农找装广显吧阿李标谈吃图念六引历首医局突专费号尽另周较注语仅考落青随选列武红响虽推势参希古众构房半节土投某案黑维革划敌致陈律足态护七兴派孩验责营星够章音跟志底站严巴例防族供效续施留讲型料终答紧黄绝奇察母京段依批群项故按河米围江织害斗双境客纪采举杀攻父苏密低朝友诉止细愿千值仍男钱破网热助倒育属坐帝限船脸职速刻乐否刚威毛状率甚独球般普怕弹校苦创假久错承印晚兰试股拿脑预谁益阳若哪微尼继送急血惊伤素药适波夜省初喜卫源食险待述陆习置居劳财环排福纳欢雷警获模充负云停木游龙树疑层冷洲冲射略范竟句室异激汉村哈策演简卡罪判担州静退既衣您宗积余痛检差富灵协角占配征修皮挥胜降阶审沉坚善妈刘读超免压银买皇养伊怀执副乱抗犯追帮宣佛岁航优怪香著田铁控税左右份穿艺背阵草脚概恶块顿敢守酒岛托央户烈洋哥索胡款靠评版宝座释景顾弟登货互付伯慢欧换闻危忙核暗姐介坏讨丽良序升监临亮露永呼味野架域沙掉括舰鱼杂误湾吉减编楚肯测败屋跑梦散温困剑渐封救贵枪缺楼县尚毫移娘朋画班智亦耳恩短掌恐遗固席松秘谢鲁遇康虑幸均销钟诗藏赶剧票损忽巨炮旧端探湖录叶春乡附吸予礼港雨呀板庭妇归睛饭额含顺输摇招婚脱补谓督毒油疗旅泽材灭逐莫笔亡鲜词圣择寻厂睡博勒烟授诺伦岸奥唐卖俄炸载洛健堂旁宫喝借君禁阴园谋宋避抓荣姑孙逃牙束跳顶玉镇雪午练迫爷篇肉嘴馆遍凡础洞卷坦牛宁纸诸训私庄祖丝翻暴森塔默握戏隐熟骨访弱蒙歌店鬼软典欲萨伙遭盘爸扩盖弄雄稳忘亿刺拥徒姆杨齐赛趣曲刀床迎冰虚玩析窗醒妻透购替塞努休虎扬途侵刑绿迅套贸毕唯谷轮库迹尤竞街促延震弃甲伟麻川申缓潜闪售灯针哲络抵朱埃抱鼓植纯夏忍页杰筑折郑贝尊吴秀混臣雅振染盛怒舞圆搞狂措姓残秋培迷诚宽宇猛摆梅毁伸摩盟末乃悲拍丁赵硬麦蒋操耶阻订彩抽赞魔纷沿喊违妹浪汇币丰蓝殊献桌啦瓦莱援译夺汽烧距裁偏符勇触课敬哭懂墙袭召罚侠厅拜巧侧韩冒债曼融惯享戴童犹乘挂奖绍厚纵障讯涉彻刊丈爆乌役描洗玛患妙镜唱烦签仙彼弗症仿倾牌陷鸟轰咱菜闭奋庆柳',
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 交接文档 ALG-2 的评分函数:越像正常中文,分越高。
|
|
59
|
+
* 在文档基础上增加「高频字」加分,用于解决短名单上 gbk/big5 区分度不足。
|
|
60
|
+
* @param {string[]} names 解码后的名字
|
|
61
|
+
* @returns {number} 得分
|
|
62
|
+
*/
|
|
63
|
+
export function scoreNames(names) {
|
|
64
|
+
let score = 0;
|
|
65
|
+
for (const name of names) {
|
|
66
|
+
for (const ch of name) {
|
|
67
|
+
const code = ch.codePointAt(0);
|
|
68
|
+
if (code >= 0x4e00 && code <= 0x9fff) {
|
|
69
|
+
score += 3; // 常用汉字
|
|
70
|
+
if (COMMON_HANZI.has(ch)) score += 2; // 高频字:自然中文比例远高于误解码生僻字
|
|
71
|
+
} else if (code < 0x80) score += 1; // ASCII
|
|
72
|
+
else if (code >= 0xff01 && code <= 0xff60) score += 1; // 全角符号
|
|
73
|
+
else if (code >= 0x3400 && code <= 0x4dbf) score += 2; // 扩展 A
|
|
74
|
+
else if (code >= 0x0100 && code <= 0x07ff) score -= 2; // 拉丁扩展/西里尔/阿拉伯(典型误解码产物)
|
|
75
|
+
else if (code >= 0xe000 && code <= 0xf8ff) score -= 6; // 私用区:误解码典型产物
|
|
76
|
+
else if (code >= 0xf900 && code <= 0xfaff) score -= 2; // 兼容汉字:误解码高频出现
|
|
77
|
+
else if (code === 0xfffd) score -= 10; // 替换字符
|
|
78
|
+
else score -= 1;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return score;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 名字里是否有「CP437 误解码」的典型字形。 */
|
|
85
|
+
export function hasCp437Marker(name) {
|
|
86
|
+
for (const ch of name) if (CP437_DISTINCTIVE.has(ch)) return true;
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 名字里是否有 Latin-1 误解码的典型痕迹(C1 控制区或 Ã/Â 系列)。 */
|
|
91
|
+
export function hasLatin1Marker(name) {
|
|
92
|
+
if (/[\u0080-\u009f]/.test(name)) return true;
|
|
93
|
+
if (/[ÃÂ][\u0080-\u00bf]/.test(name)) return true;
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 名字是否已被二次损坏(锟斤拷型:U+FFFD 的 UTF-8 字节又被当成 GBK 解读)。 */
|
|
98
|
+
export function isDoubleMojibake(name) {
|
|
99
|
+
return name.includes('锟斤拷') || name.includes('烫烫烫') || name.includes('屯屯屯');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 单个名字的形态分类(适用于已解压目录,或 ZIP 解码后的名字复核)。
|
|
104
|
+
* @param {string} name 名字
|
|
105
|
+
* @returns {{form: 'ascii'|'clean'|'A'|'A2'|'irreversible'|'double'|'unknown', fixed?: string, chain?: string, fffd?: number, markers?: string[]}}
|
|
106
|
+
*/
|
|
107
|
+
export function classifyName(name) {
|
|
108
|
+
const fffd = countFffd(name);
|
|
109
|
+
if (fffd > 0) return { form: 'irreversible', fffd };
|
|
110
|
+
if (isDoubleMojibake(name)) return { form: 'double' };
|
|
111
|
+
if (isAscii(name)) return { form: 'ascii' };
|
|
112
|
+
const reversed = tryReverseName(name);
|
|
113
|
+
if (reversed) {
|
|
114
|
+
const markers = [];
|
|
115
|
+
if (hasCp437Marker(name)) markers.push('cp437-marker');
|
|
116
|
+
if (hasLatin1Marker(name)) markers.push('latin1-marker');
|
|
117
|
+
return { form: reversed.chain.startsWith('cp437') ? 'A' : 'A2', fixed: reversed.fixed, chain: reversed.chain, markers };
|
|
118
|
+
}
|
|
119
|
+
if (cjkRatio(name) >= 0.6) return { form: 'clean' };
|
|
120
|
+
return { form: 'unknown' };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 形态 A 反解:把误解码字符串还原为原始字节,再按 GBK/GB18030 解码。
|
|
125
|
+
* @param {string} name 误解码名字
|
|
126
|
+
* @param {{chains?: ReadonlyArray<{from: string, to: string}>}} [options]
|
|
127
|
+
* @returns {{fixed: string, chain: string}|null}
|
|
128
|
+
*/
|
|
129
|
+
export function tryReverseName(name, { chains = DIR_REVERSE_CHAINS } = {}) {
|
|
130
|
+
for (const chain of chains) {
|
|
131
|
+
const bytes = tryEncode(name, chain.from);
|
|
132
|
+
if (bytes === null) continue;
|
|
133
|
+
const candidate = tryDecode(bytes, chain.to);
|
|
134
|
+
if (candidate === null || candidate === name) continue;
|
|
135
|
+
if (!looksLikeChineseText(candidate)) continue;
|
|
136
|
+
// 反解后的非法路径字符由调用方过滤,这里只保证是通顺中文
|
|
137
|
+
return { fixed: candidate, chain: `${chain.from}→${chain.to}` };
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/* ------------------------------------------------------------------ *
|
|
143
|
+
* ZIP 条目嗅探
|
|
144
|
+
* ------------------------------------------------------------------ */
|
|
145
|
+
|
|
146
|
+
function nonAsciiBytes(bytes) {
|
|
147
|
+
for (const byte of bytes) if (byte > 0x7f) return true;
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 嗅探一个 ZIP 的条目名编码,并解码全部条目名。
|
|
153
|
+
*
|
|
154
|
+
* 规则(§5.1 + §6.5 ALG-2):
|
|
155
|
+
* 1. 全部 ASCII → 无需修复;
|
|
156
|
+
* 2. 全部非 ASCII 条目都置位 0x0800 → 已合规;
|
|
157
|
+
* 3. 未置位条目按 utf-8/gbk/gb18030/big5 做严格整组解码,成功率 + 中文得分排序;
|
|
158
|
+
* 4. 最高分是 utf-8 → 名字本身已是 UTF-8,只是漏置位(仍需重建 ZIP)。
|
|
159
|
+
*
|
|
160
|
+
* @param {Array<object>} entries ZipCatalog 条目
|
|
161
|
+
* @param {{encoding?: string}} [options] 强制指定编码(跳过嗅探,仍做解码校验)
|
|
162
|
+
* @returns {{
|
|
163
|
+
* encoding: string|null,
|
|
164
|
+
* method: 'empty'|'ascii'|'declared-utf8'|'sniffed'|'forced'|'undecodable',
|
|
165
|
+
* confidence: 'high'|'medium'|'low',
|
|
166
|
+
* scores: Record<string, number>,
|
|
167
|
+
* rejections: Record<string, string>,
|
|
168
|
+
* nonAsciiEntries: number,
|
|
169
|
+
* declaredUtf8Entries: number,
|
|
170
|
+
* names: Array<{entry: object, name: string, lossy: boolean}>,
|
|
171
|
+
* warnings: string[]
|
|
172
|
+
* }}
|
|
173
|
+
*/
|
|
174
|
+
export function sniffZipEncoding(entries, { encoding } = {}) {
|
|
175
|
+
const warnings = [];
|
|
176
|
+
const nonAscii = entries.filter((entry) => nonAsciiBytes(entry.nameBytes));
|
|
177
|
+
const declaredUtf8Entries = entries.filter((entry) => entry.utf8Flag).length;
|
|
178
|
+
const forced = normalizeEncoding(encoding);
|
|
179
|
+
const result = {
|
|
180
|
+
encoding: null,
|
|
181
|
+
method: 'empty',
|
|
182
|
+
confidence: 'low',
|
|
183
|
+
scores: {},
|
|
184
|
+
rejections: {},
|
|
185
|
+
nonAsciiEntries: nonAscii.length,
|
|
186
|
+
declaredUtf8Entries,
|
|
187
|
+
names: [],
|
|
188
|
+
warnings,
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const decodeEntries = (enc) => {
|
|
192
|
+
const names = [];
|
|
193
|
+
for (const entry of entries) {
|
|
194
|
+
if (entry.utf8Flag) {
|
|
195
|
+
const declared = tryDecode(entry.nameBytes, 'utf-8');
|
|
196
|
+
if (declared === null) {
|
|
197
|
+
warnings.push(`条目 ${entry.index} 声明 UTF-8 但字节非法,已按替换字符处理`);
|
|
198
|
+
names.push({ entry, name: decodeUtf8Replacement(entry.nameBytes), lossy: true });
|
|
199
|
+
} else {
|
|
200
|
+
names.push({ entry, name: declared, lossy: false });
|
|
201
|
+
}
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const decoded = tryDecode(entry.nameBytes, enc);
|
|
205
|
+
if (decoded !== null) names.push({ entry, name: decoded, lossy: false });
|
|
206
|
+
else {
|
|
207
|
+
// 兜底:先试 utf-8,再试 GBK,最后替换字符(保留信息,标记 lossy)
|
|
208
|
+
const fallback = tryDecode(entry.nameBytes, 'utf-8') ?? tryDecode(entry.nameBytes, 'gbk');
|
|
209
|
+
if (fallback === null) {
|
|
210
|
+
names.push({ entry, name: decodeUtf8Replacement(entry.nameBytes), lossy: true });
|
|
211
|
+
warnings.push(`条目 ${entry.index} 无法按 ${enc} 解码,已使用替换字符`);
|
|
212
|
+
} else {
|
|
213
|
+
names.push({ entry, name: fallback, lossy: true });
|
|
214
|
+
warnings.push(`条目 ${entry.index} 无法按 ${enc} 解码,已回退 UTF-8/GBK`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return names;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
if (entries.length === 0) {
|
|
222
|
+
result.method = 'empty';
|
|
223
|
+
result.names = [];
|
|
224
|
+
return result;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (nonAscii.length === 0) {
|
|
228
|
+
result.encoding = 'ascii';
|
|
229
|
+
result.method = 'ascii';
|
|
230
|
+
result.confidence = 'high';
|
|
231
|
+
result.names = decodeEntries('latin-1');
|
|
232
|
+
return result;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (forced !== undefined && forced !== 'auto' && DECODE_ENCODINGS.includes(forced)) {
|
|
236
|
+
result.encoding = forced;
|
|
237
|
+
result.method = 'forced';
|
|
238
|
+
result.confidence = 'high';
|
|
239
|
+
result.names = decodeEntries(forced);
|
|
240
|
+
return result;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const undeclared = nonAscii.filter((entry) => !entry.utf8Flag);
|
|
244
|
+
if (undeclared.length === 0) {
|
|
245
|
+
result.encoding = 'utf-8';
|
|
246
|
+
result.method = 'declared-utf8';
|
|
247
|
+
result.confidence = 'high';
|
|
248
|
+
result.names = decodeEntries('utf-8');
|
|
249
|
+
return result;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const rawList = undeclared.map((entry) => entry.nameBytes);
|
|
253
|
+
/** @type {Array<{encoding: string, score: number, names: string[]}>} */
|
|
254
|
+
const viable = [];
|
|
255
|
+
for (const candidate of SNIFF_CANDIDATES) {
|
|
256
|
+
const decoded = [];
|
|
257
|
+
let ok = true;
|
|
258
|
+
for (const bytes of rawList) {
|
|
259
|
+
const text = tryDecode(bytes, candidate);
|
|
260
|
+
if (text === null) {
|
|
261
|
+
ok = false;
|
|
262
|
+
result.rejections[candidate] = '存在非法字节序列,整组解码失败';
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
decoded.push(text);
|
|
266
|
+
}
|
|
267
|
+
if (!ok) continue;
|
|
268
|
+
const score = scoreNames(decoded);
|
|
269
|
+
result.scores[candidate] = score;
|
|
270
|
+
viable.push({ encoding: candidate, score, names: decoded });
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (viable.length === 0) {
|
|
274
|
+
result.method = 'undecodable';
|
|
275
|
+
result.encoding = null;
|
|
276
|
+
result.names = decodeEntries('latin-1');
|
|
277
|
+
warnings.push('所有候选编码都无法严格解码文件名,可能需要人工指定 encoding(如 shift_jis)');
|
|
278
|
+
return result;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const utf8 = viable.find((item) => item.encoding === 'utf-8');
|
|
282
|
+
if (utf8 !== undefined) {
|
|
283
|
+
result.encoding = 'utf-8';
|
|
284
|
+
result.method = 'sniffed';
|
|
285
|
+
result.confidence = 'high';
|
|
286
|
+
result.names = decodeEntries('utf-8');
|
|
287
|
+
return result;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// gbk 与 gb18030 得分通常相同:按候选顺序稳定取 gbk。
|
|
291
|
+
let best = viable[0];
|
|
292
|
+
for (const item of viable) if (item.score > best.score) best = item;
|
|
293
|
+
// 同名次时优先 gbk(SNIFF_CANDIDATES 顺序已隐含,此处仅作显式保证)
|
|
294
|
+
if (best.encoding === 'gb18030' && result.scores.gbk === best.score) {
|
|
295
|
+
best = viable.find((item) => item.encoding === 'gbk') ?? best;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const others = viable.filter((item) => {
|
|
299
|
+
if (item.encoding === best.encoding) return false;
|
|
300
|
+
// gbk 是 gb18030 的子集,二者得分相同属正常现象,不作为区分度参考
|
|
301
|
+
if (best.encoding === 'gbk' && item.encoding === 'gb18030') return false;
|
|
302
|
+
if (best.encoding === 'gb18030' && item.encoding === 'gbk') return false;
|
|
303
|
+
return true;
|
|
304
|
+
});
|
|
305
|
+
const runnerUp = others.reduce((max, item) => (item.score > max ? item.score : max), -Infinity);
|
|
306
|
+
const ratio = runnerUp <= 0 ? Number.POSITIVE_INFINITY : best.score / runnerUp;
|
|
307
|
+
let confidence = 'low';
|
|
308
|
+
if (best.score > 0 && ratio >= 1.4) confidence = 'high';
|
|
309
|
+
else if (best.score > 0 && ratio >= 1.1) confidence = 'medium';
|
|
310
|
+
if (rawList.length < 3 && confidence !== 'low') {
|
|
311
|
+
// 条目很少时区分度低(案例 3:gbk 与 big5 仅差 33 分),主动降级并提示复核
|
|
312
|
+
confidence = confidence === 'high' ? 'medium' : 'low';
|
|
313
|
+
warnings.push('非 ASCII 条目少于 3 个,编码判定置信度有限,建议人工复核或显式指定 encoding');
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
result.encoding = best.encoding;
|
|
317
|
+
result.method = 'sniffed';
|
|
318
|
+
result.confidence = confidence;
|
|
319
|
+
result.names = decodeEntries(best.encoding);
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/* ------------------------------------------------------------------ *
|
|
324
|
+
* 路径安全与顶层目录剥离
|
|
325
|
+
* ------------------------------------------------------------------ */
|
|
326
|
+
|
|
327
|
+
/** Windows 非法文件名字符(不含路径分隔符,路径分隔符单独处理)。 */
|
|
328
|
+
const ILLEGAL_NAME_CHARS = /[<>:"|?*\u0000-\u001f]/g;
|
|
329
|
+
/** Windows 保留设备名(不能作为文件名主干)。 */
|
|
330
|
+
const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* 单个路径段的 Windows 安全化:替换非法字符、去掉尾部点/空格、规避保留设备名。
|
|
334
|
+
* @param {string} segment 原始路径段
|
|
335
|
+
* @returns {string} 可落盘的路径段
|
|
336
|
+
*/
|
|
337
|
+
export function sanitizePathSegment(segment) {
|
|
338
|
+
let result = segment.replace(ILLEGAL_NAME_CHARS, '_');
|
|
339
|
+
result = result.replace(/[. ]+$/g, '');
|
|
340
|
+
if (result.length === 0) result = '_';
|
|
341
|
+
if (WINDOWS_RESERVED.test(result)) result = `_${result}`;
|
|
342
|
+
return result;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 规范化 ZIP 条目名:统一分隔符、剔除危险路径段、替换非法字符。
|
|
347
|
+
* @param {string} raw 解码后的条目名
|
|
348
|
+
* @returns {{safe: boolean, name: string, reason?: string}}
|
|
349
|
+
*/
|
|
350
|
+
export function sanitizeEntryName(raw) {
|
|
351
|
+
const name = raw.replace(/\\/g, '/');
|
|
352
|
+
if (name.length === 0) return { safe: false, name, reason: '空文件名' };
|
|
353
|
+
if (name.startsWith('/') || /^[A-Za-z]:/.test(name)) {
|
|
354
|
+
return { safe: false, name, reason: '绝对路径条目(ZIP Slip 风险)' };
|
|
355
|
+
}
|
|
356
|
+
const segments = name.split('/');
|
|
357
|
+
const cleaned = [];
|
|
358
|
+
for (const segment of segments) {
|
|
359
|
+
if (segment === '' || segment === '.') continue;
|
|
360
|
+
if (segment === '..') return { safe: false, name, reason: '含 .. 路径段(ZIP Slip 风险)' };
|
|
361
|
+
cleaned.push(sanitizePathSegment(segment));
|
|
362
|
+
}
|
|
363
|
+
if (cleaned.length === 0) return { safe: false, name, reason: '规范化后为空' };
|
|
364
|
+
const isDir = name.endsWith('/');
|
|
365
|
+
const joined = cleaned.join('/');
|
|
366
|
+
return { safe: true, name: isDir ? `${joined}/` : joined };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* 检测 ZIP 是否把所有条目都包在与 ZIP 同名的顶层目录里(常见于「压缩为 ZIP」)。
|
|
371
|
+
* @param {Array<{name: string}>} names 解码后的条目名
|
|
372
|
+
* @param {string} zipPath ZIP 路径
|
|
373
|
+
* @returns {string} 需要剥离的前缀(含末尾 '/'),无则空串
|
|
374
|
+
*/
|
|
375
|
+
export function detectRedundantRoot(names, zipPath) {
|
|
376
|
+
const base = zipPath.replace(/[\\/]/g, '/').split('/').pop() ?? '';
|
|
377
|
+
const stem = base.replace(/\.zip$/i, '');
|
|
378
|
+
if (stem.length === 0) return '';
|
|
379
|
+
const prefix = `${stem}/`;
|
|
380
|
+
const nonEmpty = names.filter((item) => item.name.length > 0);
|
|
381
|
+
if (nonEmpty.length === 0) return '';
|
|
382
|
+
return nonEmpty.every((item) => item.name === prefix || item.name.startsWith(prefix)) ? prefix : '';
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* 判断条目解码后是否「仍然可疑」:含替换字符、CP437/Latin-1 痕迹、二次损坏。
|
|
387
|
+
* @param {string} name 名字
|
|
388
|
+
* @returns {string[]} 命中的可疑标记
|
|
389
|
+
*/
|
|
390
|
+
export function suspicionMarkers(name) {
|
|
391
|
+
const markers = [];
|
|
392
|
+
if (hasFffd(name)) markers.push('U+FFFD');
|
|
393
|
+
if (hasCp437Marker(name)) markers.push('CP437 框线字符');
|
|
394
|
+
if (hasLatin1Marker(name)) markers.push('Latin-1 高位字符');
|
|
395
|
+
if (isDoubleMojibake(name)) markers.push('二次损坏(锟斤拷)');
|
|
396
|
+
return markers;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 汇总一组名字的形态计数。
|
|
401
|
+
* @param {Array<{name: string}>} names 名字列表
|
|
402
|
+
* @returns {{ascii: number, clean: number, reversibleA: number, reversibleA2: number, irreversible: number, double: number, unknown: number}}
|
|
403
|
+
*/
|
|
404
|
+
export function summarizeForms(names) {
|
|
405
|
+
const stats = { ascii: 0, clean: 0, reversibleA: 0, reversibleA2: 0, irreversible: 0, double: 0, unknown: 0 };
|
|
406
|
+
for (const item of names) {
|
|
407
|
+
const form = item.form ?? classifyName(item.name).form;
|
|
408
|
+
switch (form) {
|
|
409
|
+
case 'ascii':
|
|
410
|
+
stats.ascii++;
|
|
411
|
+
break;
|
|
412
|
+
case 'clean':
|
|
413
|
+
stats.clean++;
|
|
414
|
+
break;
|
|
415
|
+
case 'A':
|
|
416
|
+
stats.reversibleA++;
|
|
417
|
+
break;
|
|
418
|
+
case 'A2':
|
|
419
|
+
stats.reversibleA2++;
|
|
420
|
+
break;
|
|
421
|
+
case 'irreversible':
|
|
422
|
+
stats.irreversible++;
|
|
423
|
+
break;
|
|
424
|
+
case 'double':
|
|
425
|
+
stats.double++;
|
|
426
|
+
break;
|
|
427
|
+
default:
|
|
428
|
+
stats.unknown++;
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return stats;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** 让 CP437 解码一份字节(供测试与报告展示)。 */
|
|
436
|
+
export { decodeCp437, decodeBytes, encodeText };
|