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,369 @@
1
+ /**
2
+ * 编码原语:ZIP 中文文件名乱码修复所需的全部编解码。
3
+ *
4
+ * - GBK / GB18030 / Big5:使用 Node 内置 WHATWG `TextDecoder`(无第三方依赖)。
5
+ * - CP437:ZIP 规范对「未声明编码」的默认解释,WHATWG 不收录,自带 128 字符码表。
6
+ * - CP1252 / Latin-1:自带码表(CP1252 的 0x80–0x9F 段)。
7
+ * - GBK 编码器:启动时用 `TextDecoder('gbk')` 反向生成「Unicode 字符 → 原始字节」表,
8
+ * 因此与 Python `str.encode('gbk')` 对全部 2 字节序列逐条一致(已实测 21791 条全等)。
9
+ *
10
+ * 本文件不读写磁盘,纯函数,便于独立测试。
11
+ */
12
+
13
+ /** CP437 字节 0x80–0xFF 对应的 Unicode 字符,共 128 个(末尾 U+00A0)。 */
14
+ const CP437_HIGH =
15
+ 'ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐' +
16
+ '└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00A0';
17
+
18
+ if (CP437_HIGH.length !== 128) {
19
+ throw new Error(`CP437 码表长度应为 128,实际 ${CP437_HIGH.length}`);
20
+ }
21
+
22
+ /** CP1252 字节 0x80–0x9F 中已定义的位置(0x81/0x8D/0x8F/0x90/0x9D 未定义)。 */
23
+ const CP1252_C1 = new Map([
24
+ [0x80, '\u20AC'], [0x82, '\u201A'], [0x83, '\u0192'], [0x84, '\u201E'],
25
+ [0x85, '\u2026'], [0x86, '\u2020'], [0x87, '\u2021'], [0x88, '\u02C6'],
26
+ [0x89, '\u2030'], [0x8a, '\u0160'], [0x8b, '\u2039'], [0x8c, '\u0152'],
27
+ [0x8e, '\u017D'], [0x91, '\u2018'], [0x92, '\u2019'], [0x93, '\u201C'],
28
+ [0x94, '\u201D'], [0x95, '\u2022'], [0x96, '\u2013'], [0x97, '\u2014'],
29
+ [0x98, '\u02DC'], [0x99, '\u2122'], [0x9a, '\u0161'], [0x9b, '\u203A'],
30
+ [0x9c, '\u0153'], [0x9e, '\u017E'], [0x9f, '\u0178'],
31
+ ]);
32
+
33
+ /** 可被解码的编码名(对外承诺的集合)。 */
34
+ export const DECODE_ENCODINGS = Object.freeze(['utf-8', 'gbk', 'gb18030', 'big5']);
35
+
36
+ /** 可被编码的编码名(指纹验证只需要这些)。 */
37
+ export const ENCODE_ENCODINGS = Object.freeze(['utf-8', 'gbk', 'cp437', 'latin-1', 'cp1252']);
38
+
39
+ const decoderCache = new Map();
40
+
41
+ /** 取(并缓存)一个 TextDecoder;不支持的编码名抛错。 */
42
+ function textDecoder(label, fatal) {
43
+ const key = `${label}:${fatal ? 'fatal' : 'replace'}`;
44
+ let dec = decoderCache.get(key);
45
+ if (dec === undefined) {
46
+ dec = new TextDecoder(label, { fatal });
47
+ decoderCache.set(key, dec);
48
+ }
49
+ return dec;
50
+ }
51
+
52
+ /** 把「latin-1 / cp1252 / cp437 / utf-8 / gbk / gb18030 / big5」统一成内部编码名。 */
53
+ export function normalizeEncoding(encoding) {
54
+ const key = String(encoding ?? '').trim().toLowerCase().replace(/[_\s]/g, '-');
55
+ switch (key) {
56
+ case 'utf8':
57
+ case 'utf-8':
58
+ return 'utf-8';
59
+ case 'gbk':
60
+ case 'cp936':
61
+ case 'gb2312':
62
+ case 'gb-2312':
63
+ return 'gbk';
64
+ case 'gb18030':
65
+ case 'gb-18030':
66
+ return 'gb18030';
67
+ case 'big5':
68
+ return 'big5';
69
+ case 'cp437':
70
+ case 'ibm437':
71
+ case '437':
72
+ return 'cp437';
73
+ case 'latin1':
74
+ case 'latin-1':
75
+ case 'iso-8859-1':
76
+ return 'latin-1';
77
+ case 'cp1252':
78
+ case 'windows-1252':
79
+ return 'cp1252';
80
+ case 'auto':
81
+ case '':
82
+ return 'auto';
83
+ default:
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * 严格解码字节串。
90
+ * @param {Uint8Array|Buffer} bytes 原始字节
91
+ * @param {string} encoding 编码名
92
+ * @returns {string} 解码文本
93
+ * @throws {Error} 字节在该编码下非法时
94
+ */
95
+ export function decodeBytes(bytes, encoding) {
96
+ const enc = normalizeEncoding(encoding);
97
+ switch (enc) {
98
+ case 'utf-8':
99
+ try {
100
+ return textDecoder('utf-8', true).decode(bytes);
101
+ } catch {
102
+ throw new Error('字节不是合法的 UTF-8 序列');
103
+ }
104
+ case 'gbk':
105
+ case 'gb18030':
106
+ case 'big5':
107
+ try {
108
+ return textDecoder(enc, true).decode(bytes);
109
+ } catch {
110
+ throw new Error(`字节不是合法的 ${enc} 序列`);
111
+ }
112
+ case 'cp437':
113
+ return decodeCp437(bytes);
114
+ case 'latin-1': {
115
+ let out = '';
116
+ for (const byte of bytes) out += String.fromCharCode(byte);
117
+ return out;
118
+ }
119
+ case 'cp1252':
120
+ return decodeCp1252(bytes);
121
+ default:
122
+ throw new Error(`不支持的编码:${encoding}`);
123
+ }
124
+ }
125
+
126
+ /**
127
+ * 宽松解码:非法字节替换为 U+FFFD 而不是抛错(仅 UTF-8 语义需要精确对齐时使用)。
128
+ * @param {Uint8Array|Buffer} bytes 原始字节
129
+ * @returns {string} 解码文本
130
+ */
131
+ export function decodeUtf8Replacement(bytes) {
132
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('utf8');
133
+ }
134
+
135
+ /** CP437 解码(单字节编码,1 字节 ↔ 1 字符,无损)。 */
136
+ export function decodeCp437(bytes) {
137
+ let out = '';
138
+ for (const byte of bytes) {
139
+ out += byte < 0x80 ? String.fromCharCode(byte) : CP437_HIGH[byte - 0x80];
140
+ }
141
+ return out;
142
+ }
143
+
144
+ /** CP1252 解码。未定义字节在严格模式下抛错。 */
145
+ export function decodeCp1252(bytes) {
146
+ let out = '';
147
+ for (const byte of bytes) {
148
+ if (byte < 0x80 || byte >= 0xa0) out += String.fromCharCode(byte);
149
+ else {
150
+ const mapped = CP1252_C1.get(byte);
151
+ if (mapped === undefined) throw new Error(`CP1252 字节 0x${byte.toString(16)} 未定义`);
152
+ out += mapped;
153
+ }
154
+ }
155
+ return out;
156
+ }
157
+
158
+ /** 尝试严格解码,失败返回 null。 */
159
+ export function tryDecode(bytes, encoding) {
160
+ try {
161
+ return decodeBytes(bytes, encoding);
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ /* ------------------------------------------------------------------ *
168
+ * 编码(用于生成「编码指纹」与 CP437/Latin-1 反解)
169
+ * ------------------------------------------------------------------ */
170
+
171
+ const CP437_TO_BYTE = new Map();
172
+ for (let i = 0; i < 128; i++) {
173
+ const ch = CP437_HIGH[i];
174
+ if (!CP437_TO_BYTE.has(ch)) CP437_TO_BYTE.set(ch, 0x80 + i);
175
+ }
176
+
177
+ const CP1252_TO_BYTE = new Map();
178
+ for (const [byte, ch] of CP1252_C1) {
179
+ if (!CP1252_TO_BYTE.has(ch)) CP1252_TO_BYTE.set(ch, byte);
180
+ }
181
+
182
+ /** @type {Map<string, Buffer>|null} GBK 字符 → 原始字节(惰性构建,只建一次) */
183
+ let gbkReverse = null;
184
+
185
+ /** 用 WHATWG GBK 解码器反向构建「字符 → 字节」表。 */
186
+ function buildGbkReverse() {
187
+ const map = new Map();
188
+ for (let byte = 0; byte < 0x80; byte++) {
189
+ map.set(String.fromCharCode(byte), Buffer.from([byte]));
190
+ }
191
+ const dec = textDecoder('gbk', false);
192
+ // 单字节 0x80:WHATWG GBK 映射为 €,Python gbk 亦支持;不支持则跳过。
193
+ const euro = dec.decode(Buffer.from([0x80]));
194
+ if (euro.length === 1 && euro !== '\uFFFD' && !map.has(euro)) {
195
+ map.set(euro, Buffer.from([0x80]));
196
+ }
197
+ // 双字节区:按 lead/trail 升序扫描,保证同一字符取最小字节序列。
198
+ for (let lead = 0x81; lead <= 0xfe; lead++) {
199
+ for (let trail = 0x40; trail <= 0xfe; trail++) {
200
+ if (trail === 0x7f) continue;
201
+ const s = dec.decode(Buffer.from([lead, trail]));
202
+ if (s.length !== 1 || s === '\uFFFD') continue;
203
+ if (!map.has(s)) map.set(s, Buffer.from([lead, trail]));
204
+ }
205
+ }
206
+ return map;
207
+ }
208
+
209
+ const utf8Encoder = new TextEncoder();
210
+
211
+ /**
212
+ * 严格编码文本为字节串。
213
+ * @param {string} text 文本
214
+ * @param {string} encoding 编码名;支持 utf-8 / gbk / cp437 / latin-1 / cp1252
215
+ * @returns {Buffer} 原始字节
216
+ * @throws {Error} 存在该编码无法表示的字符时
217
+ */
218
+ export function encodeText(text, encoding) {
219
+ const enc = normalizeEncoding(encoding);
220
+ switch (enc) {
221
+ case 'utf-8':
222
+ return Buffer.from(utf8Encoder.encode(text));
223
+ case 'gbk': {
224
+ gbkReverse ??= buildGbkReverse();
225
+ const parts = [];
226
+ let offset = 0;
227
+ for (const ch of text) {
228
+ const bytes = gbkReverse.get(ch);
229
+ if (bytes === undefined) {
230
+ const cp = ch.codePointAt(0);
231
+ throw new Error(
232
+ `字符 ${JSON.stringify(ch)}(U+${cp.toString(16).toUpperCase().padStart(4, '0')})无法用 GBK 编码`,
233
+ );
234
+ }
235
+ parts.push(bytes);
236
+ offset++;
237
+ }
238
+ void offset;
239
+ return Buffer.concat(parts);
240
+ }
241
+ case 'cp437': {
242
+ const out = Buffer.allocUnsafe(text.length);
243
+ for (let i = 0; i < text.length; i++) {
244
+ const ch = text[i];
245
+ const code = ch.charCodeAt(0);
246
+ if (code < 0x80) out[i] = code;
247
+ else {
248
+ const byte = CP437_TO_BYTE.get(ch);
249
+ if (byte === undefined) throw new Error(`字符 ${JSON.stringify(ch)} 不在 CP437 码表中`);
250
+ out[i] = byte;
251
+ }
252
+ }
253
+ return out;
254
+ }
255
+ case 'latin-1': {
256
+ const out = Buffer.allocUnsafe(text.length);
257
+ for (let i = 0; i < text.length; i++) {
258
+ const code = text.charCodeAt(i);
259
+ if (code > 0xff) throw new Error(`字符 ${JSON.stringify(text[i])} 超出 Latin-1 范围`);
260
+ out[i] = code;
261
+ }
262
+ return out;
263
+ }
264
+ case 'cp1252': {
265
+ const out = Buffer.allocUnsafe(text.length);
266
+ for (let i = 0; i < text.length; i++) {
267
+ const ch = text[i];
268
+ const code = ch.charCodeAt(0);
269
+ if (code < 0x80 || (code >= 0xa0 && code <= 0xff)) out[i] = code;
270
+ else {
271
+ const byte = CP1252_TO_BYTE.get(ch);
272
+ if (byte === undefined) throw new Error(`字符 ${JSON.stringify(ch)} 不在 CP1252 码表中`);
273
+ out[i] = byte;
274
+ }
275
+ }
276
+ return out;
277
+ }
278
+ default:
279
+ throw new Error(`不支持的编码:${encoding}`);
280
+ }
281
+ }
282
+
283
+ /** 尝试严格编码,失败返回 null。 */
284
+ export function tryEncode(text, encoding) {
285
+ try {
286
+ return encodeText(text, encoding);
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+
292
+ /* ------------------------------------------------------------------ *
293
+ * 文本形态判定(供嗅探与目录分类共用)
294
+ * ------------------------------------------------------------------ */
295
+
296
+ const CJK_RANGES = [
297
+ [0x3400, 0x4dbf], // 扩展 A
298
+ [0x4e00, 0x9fff], // 基本区
299
+ [0xf900, 0xfaff], // 兼容汉字
300
+ ];
301
+
302
+ /** 是否常用汉字(含扩展 A 与兼容区)。 */
303
+ export function isCjk(code) {
304
+ for (const [lo, hi] of CJK_RANGES) if (code >= lo && code <= hi) return true;
305
+ return false;
306
+ }
307
+
308
+ /** 是否全角符号/全角字母数字(U+FF01–U+FF60、U+FFE0–U+FFE6)。 */
309
+ export function isFullwidth(code) {
310
+ return (code >= 0xff01 && code <= 0xff60) || (code >= 0xffe0 && code <= 0xffe6);
311
+ }
312
+
313
+ /** 字符串是否纯 ASCII。 */
314
+ export function isAscii(text) {
315
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) > 0x7f) return false;
316
+ return true;
317
+ }
318
+
319
+ /** 统计 U+FFFD 的数量(字节已被销毁的硬证据)。 */
320
+ export function countFffd(text) {
321
+ let n = 0;
322
+ for (const ch of text) if (ch === '\uFFFD') n++;
323
+ return n;
324
+ }
325
+
326
+ /** 是否含 U+FFFD。 */
327
+ export function hasFffd(text) {
328
+ return text.includes('\uFFFD');
329
+ }
330
+
331
+ /**
332
+ * 文本是否「像正常中文」:非 ASCII 字符几乎全是汉字或全角符号,且至少有一个汉字。
333
+ * 这是区分「GBK 正确解码」与「误解码产物」的关键判据。
334
+ */
335
+ export function looksLikeChineseText(text) {
336
+ let nonAscii = 0;
337
+ let good = 0;
338
+ for (const ch of text) {
339
+ const code = ch.codePointAt(0);
340
+ if (code < 0x80) continue;
341
+ nonAscii++;
342
+ if (isCjk(code) || isFullwidth(code)) good++;
343
+ }
344
+ if (nonAscii === 0) return false;
345
+ return good / nonAscii >= 0.85 && good > 0;
346
+ }
347
+
348
+ /** 汉字在非 ASCII 字符中的占比(用于嗅探评分与置信度)。 */
349
+ export function cjkRatio(text) {
350
+ let nonAscii = 0;
351
+ let cjk = 0;
352
+ for (const ch of text) {
353
+ const code = ch.codePointAt(0);
354
+ if (code < 0x80) continue;
355
+ nonAscii++;
356
+ if (isCjk(code)) cjk++;
357
+ }
358
+ return nonAscii === 0 ? 0 : cjk / nonAscii;
359
+ }
360
+
361
+ /** 统计字符串的显示宽度(近似:CJK/全角算 2,其余算 1),用于报告排版。 */
362
+ export function displayWidth(text) {
363
+ let width = 0;
364
+ for (const ch of text) {
365
+ const code = ch.codePointAt(0);
366
+ width += isCjk(code) || isFullwidth(code) || code > 0xffff ? 2 : 1;
367
+ }
368
+ return width;
369
+ }