pi-charset 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/CHANGELOG.zh-CN.md +18 -0
- package/dist/config.js +943 -0
- package/dist/edit/apply-patch-core.js +274 -0
- package/dist/edit/diagnostics.js +46 -0
- package/dist/edit/hashline.js +400 -0
- package/dist/edit/patch.js +634 -0
- package/dist/edit/paths.js +48 -0
- package/dist/edit/plan.js +90 -0
- package/dist/encoding/classify.js +430 -0
- package/dist/encoding/common-scripts.js +58 -0
- package/dist/encoding/converter.js +311 -0
- package/dist/encoding/fast-codec.js +476 -0
- package/dist/encoding/file-stamp.js +32 -0
- package/dist/encoding/line-endings.js +118 -0
- package/dist/encoding/mime.js +88 -0
- package/dist/encoding/stream-transcode.js +287 -0
- package/dist/grep-core.js +730 -0
- package/dist/journal.js +494 -0
- package/dist/maintenance.js +333 -0
- package/dist/mcp/server.js +866 -0
- package/dist/notify.js +60 -0
- package/dist/operations.js +1021 -0
- package/dist/path-key.js +10 -0
- package/dist/read-view.js +927 -0
- package/dist/resolve.js +325 -0
- package/dist/version.js +2 -0
- package/docs/MCP-AND-MULTI-AGENT.md +27 -19
- package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +27 -19
- package/package.json +14 -2
- package/src/edit/apply-patch-core.ts +32 -3
- package/src/grep-core.ts +50 -8
- package/src/grep.ts +9 -1
- package/src/index.ts +8 -5
- package/src/journal.ts +167 -42
- package/src/mcp/server.ts +435 -163
- package/src/operations.ts +197 -68
- package/src/read-view.ts +111 -8
- package/src/shell-guard.ts +38 -1
- package/src/version.ts +1 -1
- package/tools/pi-charset-cli.mjs +453 -167
- package/tools/pi-charset-mcp.mjs +78 -41
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { detectLineEndingKindFromText } from "../encoding/line-endings.js";
|
|
2
|
+
import { isWellFormed } from "../encoding/converter.js";
|
|
3
|
+
import { EditError, lineAt, suggestLines } from "./diagnostics.js";
|
|
4
|
+
export const hasBareCR = (text) => {
|
|
5
|
+
for (let p = text.indexOf("\r"); p !== -1; p = text.indexOf("\r", p + 1)) {
|
|
6
|
+
if (text.charCodeAt(p + 1) !== 10)
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
return false;
|
|
10
|
+
};
|
|
11
|
+
const toLF = (text) => text.replace(/\r\n/g, "\n");
|
|
12
|
+
export function assertUniformSource(before) {
|
|
13
|
+
const kind = detectLineEndingKindFromText(before);
|
|
14
|
+
if (kind === "MIXED" || (kind !== "LF" && hasBareCR(before)) || (kind === "LF" && before.includes("\r"))) {
|
|
15
|
+
throw new EditError("UNSUPPORTED_FILE", "Mixed line endings or bare CR cannot be edited losslessly (混合换行).");
|
|
16
|
+
}
|
|
17
|
+
return kind;
|
|
18
|
+
}
|
|
19
|
+
export function assertValidText(value, label, requireNonEmpty = false) {
|
|
20
|
+
if (typeof value !== "string" || (requireNonEmpty && !value) || !isWellFormed(value) || hasBareCR(value)) {
|
|
21
|
+
throw new EditError("INVALID_INPUT", `${label} must be a ${requireNonEmpty ? "nonempty " : ""}well-formed string without bare CR.`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function assertNoMixedResult(after, sourceKind, label = "Replacement") {
|
|
25
|
+
if (sourceKind === "NONE" && detectLineEndingKindFromText(after) === "MIXED") {
|
|
26
|
+
throw new EditError("INVALID_INPUT", `${label} would introduce mixed line endings.`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function normalizeReplacementEol(text, sourceKind) {
|
|
30
|
+
const lf = toLF(text);
|
|
31
|
+
return sourceKind === "CRLF" ? lf.replace(/\n/g, "\r\n") : sourceKind === "LF" ? lf : text;
|
|
32
|
+
}
|
|
33
|
+
export function planEdits(before, edits) {
|
|
34
|
+
const kind = assertUniformSource(before);
|
|
35
|
+
if (!Array.isArray(edits) || edits.length === 0) {
|
|
36
|
+
throw new EditError("INVALID_INPUT", "edits must contain at least one replacement.");
|
|
37
|
+
}
|
|
38
|
+
const ranges = edits.map((edit, index) => {
|
|
39
|
+
assertValidText(edit?.oldText, `edits[${index}].oldText`, true);
|
|
40
|
+
assertValidText(edit?.newText, `edits[${index}].newText`);
|
|
41
|
+
// Uniform line endings allow reversible request normalization without rewriting source text.
|
|
42
|
+
const oldLF = toLF(edit.oldText);
|
|
43
|
+
const target = kind === "CRLF" ? oldLF.replace(/\n/g, "\r\n") : oldLF;
|
|
44
|
+
const start = before.indexOf(target);
|
|
45
|
+
if (start === -1) {
|
|
46
|
+
throw new EditError("NOT_FOUND", `Could not exactly locate edits[${index}]. Re-read and supply the exact text.` +
|
|
47
|
+
suggestLines(before, edit.oldText));
|
|
48
|
+
}
|
|
49
|
+
const next = before.indexOf(target, start + 1);
|
|
50
|
+
if (next !== -1) {
|
|
51
|
+
throw new EditError("AMBIGUOUS_MATCH", `edits[${index}] is not unique: lines ${lineAt(before, start)} and ${lineAt(before, next)}, offsets ${start} and ${next}. Add unique context.`);
|
|
52
|
+
}
|
|
53
|
+
const end = start + target.length;
|
|
54
|
+
if ((before[start] === "\n" && before[start - 1] === "\r") ||
|
|
55
|
+
(before[end] === "\n" && before[end - 1] === "\r")) {
|
|
56
|
+
throw new EditError("INVALID_INPUT", `edits[${index}] splits a CRLF sequence.`);
|
|
57
|
+
}
|
|
58
|
+
const newLF = toLF(edit.newText);
|
|
59
|
+
const text = kind === "CRLF" ? newLF.replace(/\n/g, "\r\n") : kind === "LF" ? newLF : edit.newText;
|
|
60
|
+
return { index, start, end, text };
|
|
61
|
+
}).sort((a, b) => a.start - b.start || a.index - b.index);
|
|
62
|
+
const parts = [];
|
|
63
|
+
let pos = 0;
|
|
64
|
+
for (let i = 0; i < ranges.length; i++) {
|
|
65
|
+
const range = ranges[i];
|
|
66
|
+
if (range.start < pos) {
|
|
67
|
+
throw new EditError("OVERLAPPING_EDITS", `edits[${ranges[i - 1].index}] and edits[${range.index}] overlap in the original file.`);
|
|
68
|
+
}
|
|
69
|
+
parts.push(before.slice(pos, range.start), range.text);
|
|
70
|
+
pos = range.end;
|
|
71
|
+
}
|
|
72
|
+
parts.push(before.slice(pos));
|
|
73
|
+
const after = parts.join("");
|
|
74
|
+
assertNoMixedResult(after, kind);
|
|
75
|
+
return { before, after, ranges, changed: after !== before };
|
|
76
|
+
}
|
|
77
|
+
/** Plan a Whole-File replacement while preserving uniform CRLF/LF line endings and no-op detection. */
|
|
78
|
+
export function planWholeFile(before, content) {
|
|
79
|
+
const kind = assertUniformSource(before);
|
|
80
|
+
assertValidText(content, "wholeFile");
|
|
81
|
+
const after = normalizeReplacementEol(content, kind);
|
|
82
|
+
assertNoMixedResult(after, kind);
|
|
83
|
+
const changed = after !== before;
|
|
84
|
+
return {
|
|
85
|
+
before,
|
|
86
|
+
after,
|
|
87
|
+
ranges: changed ? [{ index: 0, start: 0, end: before.length, text: after }] : [],
|
|
88
|
+
changed,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
// Deterministic byte-level encoding classifier:
|
|
2
|
+
// Order: empty -> BOM (utf8 / utf32->binary / utf16le / utf16be) -> NUL=binary -> force
|
|
3
|
+
// -> pure ASCII (SIMD) -> strict full-buffer UTF-8 (SIMD) -> CJK round-trip candidates -> config fallback -> unknown
|
|
4
|
+
import { isAscii, isUtf8 } from "node:buffer";
|
|
5
|
+
import { readFileSync, statSync } from "node:fs";
|
|
6
|
+
import iconv from "iconv-lite";
|
|
7
|
+
import { normalizePathKey } from "../path-key.js";
|
|
8
|
+
import { AUTO_CJK_CANDIDATES, decodeToUtf8, isSingleByteEncoding, isStatefulEncoding, normalizeEncoding, } from "./converter.js";
|
|
9
|
+
import { getCommonHan, COMMON_HANGUL, JP_KANJI, TOP_HAN } from "./common-scripts.js";
|
|
10
|
+
import { fastExactRoundTrip } from "./fast-codec.js";
|
|
11
|
+
import { sameFileStamp, stampFromStat } from "./file-stamp.js";
|
|
12
|
+
// Byte-exact round-trips do not separate CJK families: most Big5, Shift_JIS and EUC-KR text also decodes
|
|
13
|
+
// and re-encodes losslessly as GBK, as different characters. The decoded sample decides which family is
|
|
14
|
+
// real: genuine text is full of common characters, mojibake is not. Kana and Hangul settle Japanese and
|
|
15
|
+
// Korean. A thin margin marks the bytes ambiguous instead of guessing.
|
|
16
|
+
const FAMILY_REPRESENTATIVES = [
|
|
17
|
+
["GB", "GB18030"], ["Big5", "Big5"], ["Shift_JIS", "Shift_JIS"], ["EUC-KR", "EUC-KR"], ["EUC-JP", "EUC-JP"],
|
|
18
|
+
];
|
|
19
|
+
const FAMILY_OF = {
|
|
20
|
+
GB18030: "GB", GBK: "GB", GB2312: "GB", CP936: "GB", "WINDOWS-936": "GB", CSGBK: "GB",
|
|
21
|
+
BIG5: "Big5", "BIG5-HKSCS": "Big5", "SHIFT_JIS": "Shift_JIS", "SJIS": "Shift_JIS", "MS932": "Shift_JIS", "CP932": "Shift_JIS", WINDOWS_31J: "Shift_JIS",
|
|
22
|
+
"EUC-KR": "EUC-KR", "EUC-JP": "EUC-JP",
|
|
23
|
+
};
|
|
24
|
+
const SCRIPT_SAMPLE_BYTES = 8192;
|
|
25
|
+
const CONFIDENT_SCORE = 0.25;
|
|
26
|
+
const CONFIDENT_MARGIN = 0.15;
|
|
27
|
+
export const familyOf = (encoding) => FAMILY_OF[encoding.toUpperCase()] ?? encoding;
|
|
28
|
+
function scriptProfile(text) {
|
|
29
|
+
const commonHan = getCommonHan();
|
|
30
|
+
let han = 0, common = 0, top = 0, jpKanji = 0, kana = 0, hangul = 0, commonHangul = 0, fffd = 0, other = 0;
|
|
31
|
+
for (const ch of text) {
|
|
32
|
+
const c = ch.codePointAt(0);
|
|
33
|
+
if (c < 0x80)
|
|
34
|
+
continue;
|
|
35
|
+
if (c >= 0x3040 && c <= 0x30ff)
|
|
36
|
+
kana++;
|
|
37
|
+
else if (c >= 0xac00 && c <= 0xd7a3) {
|
|
38
|
+
hangul++;
|
|
39
|
+
if (COMMON_HANGUL.has(ch))
|
|
40
|
+
commonHangul++;
|
|
41
|
+
}
|
|
42
|
+
else if ((c >= 0x3400 && c <= 0x4dbf) || (c >= 0x4e00 && c <= 0x9fff) || (c >= 0x20000 && c <= 0x3134f)) {
|
|
43
|
+
han++;
|
|
44
|
+
if (commonHan.has(ch))
|
|
45
|
+
common++;
|
|
46
|
+
if (TOP_HAN.has(ch))
|
|
47
|
+
top++;
|
|
48
|
+
if (JP_KANJI.has(ch))
|
|
49
|
+
jpKanji++;
|
|
50
|
+
}
|
|
51
|
+
else if (c === 0xfffd)
|
|
52
|
+
fffd++;
|
|
53
|
+
else
|
|
54
|
+
other++;
|
|
55
|
+
}
|
|
56
|
+
return { han, common, top, jpKanji, kana, hangul, commonHangul, fffd, other };
|
|
57
|
+
}
|
|
58
|
+
function firstNonAsciiSlice(sample, maxBytes = SCRIPT_SAMPLE_BYTES) {
|
|
59
|
+
let start = 0;
|
|
60
|
+
while (start < sample.length && sample[start] < 0x80)
|
|
61
|
+
start++;
|
|
62
|
+
return sample.subarray(start, Math.min(sample.length, start + maxBytes));
|
|
63
|
+
}
|
|
64
|
+
/** Score every candidate family by decoding each buffer's first non-ASCII slice without cross-buffer byte splicing. */
|
|
65
|
+
export function decideFamilyFromBuffers(samples, families, perBufferLimit = SCRIPT_SAMPLE_BYTES) {
|
|
66
|
+
const slices = samples.map((b) => firstNonAsciiSlice(b, perBufferLimit)).filter((s) => s.length > 0);
|
|
67
|
+
if (slices.length === 0)
|
|
68
|
+
return { family: null, confident: false };
|
|
69
|
+
const scores = [];
|
|
70
|
+
for (const [family, enc] of FAMILY_REPRESENTATIVES) {
|
|
71
|
+
if (!families.has(family))
|
|
72
|
+
continue;
|
|
73
|
+
let han = 0, common = 0, top = 0, jpKanji = 0, kana = 0, hangul = 0, commonHangul = 0, fffd = 0, other = 0;
|
|
74
|
+
let ok = false;
|
|
75
|
+
for (const slice of slices) {
|
|
76
|
+
let text;
|
|
77
|
+
try {
|
|
78
|
+
text = decodeToUtf8(slice, enc);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
ok = true;
|
|
84
|
+
const p = scriptProfile(text);
|
|
85
|
+
han += p.han;
|
|
86
|
+
common += p.common;
|
|
87
|
+
top += p.top;
|
|
88
|
+
jpKanji += p.jpKanji;
|
|
89
|
+
kana += p.kana;
|
|
90
|
+
hangul += p.hangul;
|
|
91
|
+
commonHangul += p.commonHangul;
|
|
92
|
+
fffd += p.fffd;
|
|
93
|
+
other += p.other;
|
|
94
|
+
}
|
|
95
|
+
if (!ok)
|
|
96
|
+
continue;
|
|
97
|
+
const nonAscii = han + kana + hangul + fffd + other;
|
|
98
|
+
if (!nonAscii) {
|
|
99
|
+
scores.push([family, 0]);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const kanaRatio = kana / nonAscii, hangulRatio = hangul / nonAscii;
|
|
103
|
+
// Common hanzi are strong evidence, but GBK hanzi rows overlap the Hangul rows of EUC-KR, so script
|
|
104
|
+
// bonuses only count when the decoded script itself looks real: kana capped below a strong hanzi score,
|
|
105
|
+
// Hangul gated by its own frequency skew.
|
|
106
|
+
// Frequency carries twice the weight of commonness: GBK text read as Big5 still looks "common".
|
|
107
|
+
let score = common / Math.max(1, han) + (2 * top) / Math.max(1, han) - (2 * fffd) / nonAscii;
|
|
108
|
+
// Script bonuses need enough evidence: a handful of noise syllables can hit the common set by chance.
|
|
109
|
+
if ((family === "Shift_JIS" || family === "EUC-JP") && kana >= 4) {
|
|
110
|
+
// Kana rows are shared with GB2312, so the kanji decide: real Japanese kanji are common words.
|
|
111
|
+
score += Math.min(kanaRatio, 0.5) + jpKanji / Math.max(1, han);
|
|
112
|
+
}
|
|
113
|
+
if (family === "EUC-KR" && hangul >= 3) {
|
|
114
|
+
const pure = commonHangul / hangul;
|
|
115
|
+
score += hangulRatio * ((hangul >= 8 && pure >= 0.2) || pure >= 0.5 ? 1.5 : 0.2);
|
|
116
|
+
}
|
|
117
|
+
scores.push([family, score]);
|
|
118
|
+
}
|
|
119
|
+
scores.sort((a, b) => b[1] - a[1]);
|
|
120
|
+
const [best, bestScore] = scores[0] ?? [null, 0];
|
|
121
|
+
const second = scores[1]?.[1] ?? 0;
|
|
122
|
+
return { family: best, confident: scores.length > 1 && bestScore >= CONFIDENT_SCORE && bestScore - second >= CONFIDENT_MARGIN };
|
|
123
|
+
}
|
|
124
|
+
/** Score every candidate family by decoding a sample of the first non-ASCII bytes under each. */
|
|
125
|
+
export function decideFamily(sample, families) {
|
|
126
|
+
return decideFamilyFromBuffers([sample], families, SCRIPT_SAMPLE_BYTES);
|
|
127
|
+
}
|
|
128
|
+
/** Reorder candidates so the chosen family comes first; stable, so narrowest-first order holds inside it. */
|
|
129
|
+
export function preferFamily(order, family) {
|
|
130
|
+
if (!family)
|
|
131
|
+
return [...order];
|
|
132
|
+
return order.map((c, i) => ({ c, i, rank: familyOf(c) === family ? 0 : 1 }))
|
|
133
|
+
.sort((a, b) => a.rank - b.rank || a.i - b.i).map((x) => x.c);
|
|
134
|
+
}
|
|
135
|
+
export const DEFAULT_AUTO_CANDIDATES = [...AUTO_CJK_CANDIDATES];
|
|
136
|
+
/** Buffers larger than 512KB short-circuit after the first matching candidate. */
|
|
137
|
+
export const FULL_SCAN_LIMIT = 512 * 1024;
|
|
138
|
+
export const NUL_PROBE_LIMIT = 8192;
|
|
139
|
+
const startsWith = (b, sig) => {
|
|
140
|
+
for (let i = 0; i < sig.length; i++)
|
|
141
|
+
if (b[i] !== sig[i])
|
|
142
|
+
return false;
|
|
143
|
+
return true;
|
|
144
|
+
};
|
|
145
|
+
/** Check for NUL (0x00) bytes within the first `limit` bytes using native Buffer.includes. */
|
|
146
|
+
export function containsNul(b, limit = NUL_PROBE_LIMIT) {
|
|
147
|
+
const n = Math.min(b.length, limit);
|
|
148
|
+
return b.subarray(0, n).includes(0);
|
|
149
|
+
}
|
|
150
|
+
/** Check whether all bytes are ASCII (<= 0x7F) using Node's native C++ SIMD implementation. */
|
|
151
|
+
export function isAllAscii(b) {
|
|
152
|
+
return isAscii(b);
|
|
153
|
+
}
|
|
154
|
+
/** Validate the entire buffer as strict UTF-8 using Node's native C++ SIMD implementation without heap string allocation. */
|
|
155
|
+
export function isValidUtf8Strict(b) {
|
|
156
|
+
return isUtf8(b);
|
|
157
|
+
}
|
|
158
|
+
/** Check whether decoding and re-encoding under enc reproduces the exact input bytes without U+FFFD. */
|
|
159
|
+
export function exactRoundTrip(b, enc) {
|
|
160
|
+
const fast = fastExactRoundTrip(b, enc);
|
|
161
|
+
if (fast !== null)
|
|
162
|
+
return fast;
|
|
163
|
+
try {
|
|
164
|
+
const text = iconv.decode(b, enc);
|
|
165
|
+
if (text.includes("\ufffd"))
|
|
166
|
+
return false;
|
|
167
|
+
return Buffer.compare(iconv.encode(text, enc), b) === 0;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function decodeHasFffd(b, enc) {
|
|
174
|
+
try {
|
|
175
|
+
return iconv.decode(b, enc).includes("\ufffd");
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function normalizeCandidates(list) {
|
|
182
|
+
const src = list && list.length ? list : DEFAULT_AUTO_CANDIDATES;
|
|
183
|
+
const out = [];
|
|
184
|
+
for (const e of src) {
|
|
185
|
+
let n;
|
|
186
|
+
try {
|
|
187
|
+
n = normalizeEncoding(e);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
if (isSingleByteEncoding(n) || isStatefulEncoding(n))
|
|
193
|
+
continue;
|
|
194
|
+
if (!AUTO_CJK_CANDIDATES.includes(n))
|
|
195
|
+
continue;
|
|
196
|
+
if (!out.includes(n))
|
|
197
|
+
out.push(n);
|
|
198
|
+
}
|
|
199
|
+
return out.length ? out : [...DEFAULT_AUTO_CANDIDATES];
|
|
200
|
+
}
|
|
201
|
+
/** Check that a UTF-16 byte body is well-formed: even length and no unpaired surrogate code units. */
|
|
202
|
+
function isValidUtf16Body(body, littleEndian) {
|
|
203
|
+
if (body.length % 2 !== 0)
|
|
204
|
+
return false;
|
|
205
|
+
const unitAt = (i) => littleEndian ? body[i] | (body[i + 1] << 8) : (body[i] << 8) | body[i + 1];
|
|
206
|
+
for (let i = 0; i < body.length; i += 2) {
|
|
207
|
+
const unit = unitAt(i);
|
|
208
|
+
if (unit >= 0xd800 && unit <= 0xdbff) {
|
|
209
|
+
if (i + 4 > body.length)
|
|
210
|
+
return false;
|
|
211
|
+
const next = unitAt(i + 2);
|
|
212
|
+
if (!(next >= 0xdc00 && next <= 0xdfff))
|
|
213
|
+
return false;
|
|
214
|
+
i += 2;
|
|
215
|
+
}
|
|
216
|
+
else if (unit >= 0xdc00 && unit <= 0xdfff) {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
function makeVerdict(kind, encoding, extra = {}) {
|
|
223
|
+
return { kind, encoding, ambiguous: false, hasFffd: false, candidates: [], exhaustive: true, bom: false, ...extra };
|
|
224
|
+
}
|
|
225
|
+
function configVerdict(b, enc, reason) {
|
|
226
|
+
return makeVerdict("config", enc, { hasFffd: decodeHasFffd(b, enc), candidates: [enc], configReason: reason });
|
|
227
|
+
}
|
|
228
|
+
// Deciding one buffer twice inside one operation (rule inference, then the read plan) is common; the
|
|
229
|
+
// verdict is a pure function of the bytes and the options, so identical buffers share it. Weak keys let
|
|
230
|
+
// the entries die with their buffers.
|
|
231
|
+
const verdictMemo = new WeakMap();
|
|
232
|
+
export function classifyBuffer(B, cfg = null, opts = {}) {
|
|
233
|
+
const memoKey = `${cfgKeyPart(cfg)}\u0000${opts.exhaustive === false ? 0 : 1}\u0000${opts.candidateOrder?.join(",") ?? ""}`;
|
|
234
|
+
let perBuffer = verdictMemo.get(B);
|
|
235
|
+
const hit = perBuffer?.get(memoKey);
|
|
236
|
+
if (hit)
|
|
237
|
+
return hit;
|
|
238
|
+
const verdict = classifyUncached(B, cfg, opts);
|
|
239
|
+
(perBuffer ??= new Map()).set(memoKey, verdict);
|
|
240
|
+
verdictMemo.set(B, perBuffer);
|
|
241
|
+
return verdict;
|
|
242
|
+
}
|
|
243
|
+
/** The BOM, NUL, ASCII and strict UTF-8 checks that precede any candidate round-trip, as a verdict.
|
|
244
|
+
* null means the bytes need candidate testing. Mirrors the start of the original classification order. */
|
|
245
|
+
export function quickKind(B) {
|
|
246
|
+
if (B.length === 0)
|
|
247
|
+
return makeVerdict("utf8", "UTF-8");
|
|
248
|
+
if (startsWith(B, [0xef, 0xbb, 0xbf])) {
|
|
249
|
+
return isValidUtf8Strict(B.subarray(3))
|
|
250
|
+
? makeVerdict("utf8-bom", "UTF-8", { bom: true })
|
|
251
|
+
: makeVerdict("unknown", "UNKNOWN", { hasFffd: true, bom: true });
|
|
252
|
+
}
|
|
253
|
+
if (startsWith(B, [0xff, 0xfe, 0x00, 0x00]) || startsWith(B, [0x00, 0x00, 0xfe, 0xff]))
|
|
254
|
+
return makeVerdict("binary", "BINARY");
|
|
255
|
+
if (startsWith(B, [0xff, 0xfe])) {
|
|
256
|
+
return isValidUtf16Body(B.subarray(2), true)
|
|
257
|
+
? makeVerdict("utf16le", "UTF-16LE", { bom: true })
|
|
258
|
+
: makeVerdict("unknown", "UNKNOWN", { hasFffd: true, bom: true });
|
|
259
|
+
}
|
|
260
|
+
if (startsWith(B, [0xfe, 0xff])) {
|
|
261
|
+
return isValidUtf16Body(B.subarray(2), false)
|
|
262
|
+
? makeVerdict("utf16be", "UTF-16BE", { bom: true })
|
|
263
|
+
: makeVerdict("unknown", "UNKNOWN", { hasFffd: true, bom: true });
|
|
264
|
+
}
|
|
265
|
+
if (containsNul(B))
|
|
266
|
+
return makeVerdict("binary", "BINARY");
|
|
267
|
+
if (isAllAscii(B))
|
|
268
|
+
return makeVerdict("ascii", "UTF-8");
|
|
269
|
+
if (isValidUtf8Strict(B))
|
|
270
|
+
return makeVerdict("utf8", "UTF-8");
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
function classifyUncached(B, cfg, opts) {
|
|
274
|
+
const exhaustiveWanted = opts.exhaustive !== false;
|
|
275
|
+
const quick = quickKind(B);
|
|
276
|
+
if (quick) {
|
|
277
|
+
// Order preserved from the original classifier: empty, BOM and NUL verdicts stand; force then wins
|
|
278
|
+
// over plain ASCII and UTF-8 text.
|
|
279
|
+
if (B.length > 0 && !quick.bom && quick.kind !== "binary" && cfg?.force && cfg.sourceEncoding) {
|
|
280
|
+
let pref = null;
|
|
281
|
+
try {
|
|
282
|
+
pref = normalizeEncoding(cfg.sourceEncoding);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
pref = null;
|
|
286
|
+
}
|
|
287
|
+
if (pref)
|
|
288
|
+
return configVerdict(B, pref, "force");
|
|
289
|
+
}
|
|
290
|
+
// Optional legacy-first tie-breaker: on BOM-less files whose bytes satisfy both UTF-8 and the declared
|
|
291
|
+
// multi-byte CJK sourceEncoding (e.g. tiny GBK headers whose 6-byte sequences form valid UTF-8), prefer
|
|
292
|
+
// sourceEncoding instead of letting protectUtf8 lock the file as UTF-8. Real non-GBK UTF-8 stays UTF-8.
|
|
293
|
+
if (quick.kind === "utf8" && !quick.bom && cfg?.preferSourceOverUtf8 && cfg.sourceEncoding) {
|
|
294
|
+
let pref = null;
|
|
295
|
+
try {
|
|
296
|
+
pref = normalizeEncoding(cfg.sourceEncoding);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
pref = null;
|
|
300
|
+
}
|
|
301
|
+
if (pref && pref !== "UTF-8" && !isSingleByteEncoding(pref) && !isStatefulEncoding(pref) && exactRoundTrip(B, pref)) {
|
|
302
|
+
return makeVerdict("cjk", pref, { candidates: [pref], exhaustive: false });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return quick;
|
|
306
|
+
}
|
|
307
|
+
let pref = null;
|
|
308
|
+
if (cfg?.sourceEncoding) {
|
|
309
|
+
try {
|
|
310
|
+
pref = normalizeEncoding(cfg.sourceEncoding);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
pref = null;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (cfg?.force && pref)
|
|
317
|
+
return configVerdict(B, pref, "force");
|
|
318
|
+
const cands = normalizeCandidates(cfg?.autoCandidates);
|
|
319
|
+
if (pref && !cands.includes(pref)) {
|
|
320
|
+
if (isSingleByteEncoding(pref) || isStatefulEncoding(pref))
|
|
321
|
+
return configVerdict(B, pref, "undecidable");
|
|
322
|
+
}
|
|
323
|
+
const preferred = opts.candidateOrder?.filter((c) => cands.includes(c)) ?? [];
|
|
324
|
+
let order = pref && cands.includes(pref)
|
|
325
|
+
? [pref, ...cands.filter((c) => c !== pref)]
|
|
326
|
+
: preferred.length ? [...preferred, ...cands.filter((c) => !preferred.includes(c))] : cands;
|
|
327
|
+
// Without a declared preference, let the decoded sample choose the family before the round-trip loop.
|
|
328
|
+
let family = null;
|
|
329
|
+
let crossFamilyAmbiguous = false;
|
|
330
|
+
if (!(pref && cands.includes(pref)) && new Set(cands.map(familyOf)).size > 1) {
|
|
331
|
+
const decision = decideFamily(B, new Set(cands.map(familyOf)));
|
|
332
|
+
family = decision.family;
|
|
333
|
+
if (decision.confident)
|
|
334
|
+
order = preferFamily(order, family);
|
|
335
|
+
else
|
|
336
|
+
crossFamilyAmbiguous = true;
|
|
337
|
+
}
|
|
338
|
+
const pass = [];
|
|
339
|
+
let exhaustive = true;
|
|
340
|
+
for (let i = 0; i < order.length; i++) {
|
|
341
|
+
const e = order[i];
|
|
342
|
+
if (!exactRoundTrip(B, e))
|
|
343
|
+
continue;
|
|
344
|
+
pass.push(e);
|
|
345
|
+
if (pref && e === pref) {
|
|
346
|
+
exhaustive = false;
|
|
347
|
+
break;
|
|
348
|
+
}
|
|
349
|
+
// Large files and read-only callers stop at the first lossless candidate.
|
|
350
|
+
if (B.length > FULL_SCAN_LIMIT || !exhaustiveWanted) {
|
|
351
|
+
exhaustive = false;
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (pass.length === 0) {
|
|
356
|
+
if (pref && !cands.includes(pref))
|
|
357
|
+
return { ...configVerdict(B, pref, "undecidable"), kind: "config" };
|
|
358
|
+
return { kind: "unknown", encoding: "UNKNOWN", ambiguous: false, hasFffd: true, candidates: [], exhaustive: true, bom: false };
|
|
359
|
+
}
|
|
360
|
+
const chosen = pref && pass.includes(pref) ? pref : pass[0];
|
|
361
|
+
return {
|
|
362
|
+
kind: "cjk",
|
|
363
|
+
encoding: chosen,
|
|
364
|
+
ambiguous: exhaustive ? pass.length > 1 : pass.length > 1 || order.length > pass.length,
|
|
365
|
+
hasFffd: false,
|
|
366
|
+
candidates: pass,
|
|
367
|
+
exhaustive,
|
|
368
|
+
bom: false,
|
|
369
|
+
family,
|
|
370
|
+
crossFamilyAmbiguous,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
const fileCache = new Map();
|
|
374
|
+
const CFG_SEP = "\u0000";
|
|
375
|
+
function cfgKeyPart(cfg) {
|
|
376
|
+
if (!cfg)
|
|
377
|
+
return "-";
|
|
378
|
+
return `${cfg.sourceEncoding ?? "-"}|${(cfg.autoCandidates ?? []).join(",")}|${cfg.force ? 1 : 0}|${cfg.preferSourceOverUtf8 ? 1 : 0}`;
|
|
379
|
+
}
|
|
380
|
+
export function classifyFileWithRaw(absPath, cfg, opts = {}) {
|
|
381
|
+
const key = cacheKey(absPath, cfg);
|
|
382
|
+
const exhaustiveWanted = opts.exhaustive !== false;
|
|
383
|
+
let stamp;
|
|
384
|
+
try {
|
|
385
|
+
stamp = stampFromStat(statSync(absPath));
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return { verdict: classifyBuffer(Buffer.alloc(0), cfg, opts), raw: null, stamp: null };
|
|
389
|
+
}
|
|
390
|
+
const hit = fileCache.get(key);
|
|
391
|
+
// A verdict produced for a non-exhaustive request cannot answer an exhaustive one. Early exits
|
|
392
|
+
// chosen by the classifier itself (configured preference, files over the full-scan limit) are final.
|
|
393
|
+
if (hit && sameFileStamp(hit.stamp, stamp) && (!hit.limited || !exhaustiveWanted)) {
|
|
394
|
+
return { verdict: hit.verdict, raw: null, stamp };
|
|
395
|
+
}
|
|
396
|
+
const raw = readFileSync(absPath);
|
|
397
|
+
const verdict = classifyBuffer(raw, cfg, opts);
|
|
398
|
+
store(key, stamp, verdict, !exhaustiveWanted);
|
|
399
|
+
return { verdict, raw, stamp };
|
|
400
|
+
}
|
|
401
|
+
export function classifyFileCached(absPath, cfg, opts = {}) {
|
|
402
|
+
return classifyFileWithRaw(absPath, cfg, opts).verdict;
|
|
403
|
+
}
|
|
404
|
+
function cacheKey(absPath, cfg) {
|
|
405
|
+
return normalizePathKey(absPath) + CFG_SEP + cfgKeyPart(cfg);
|
|
406
|
+
}
|
|
407
|
+
function store(key, stamp, verdict, limited = false) {
|
|
408
|
+
fileCache.set(key, { stamp, verdict, limited });
|
|
409
|
+
if (fileCache.size > 20000) {
|
|
410
|
+
for (const k of [...fileCache.keys()].slice(0, 10000))
|
|
411
|
+
fileCache.delete(k);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
export function clearClassifyCache() {
|
|
415
|
+
fileCache.clear();
|
|
416
|
+
}
|
|
417
|
+
export function invalidateClassifyCache(absPath) {
|
|
418
|
+
const target = normalizePathKey(absPath);
|
|
419
|
+
for (const k of [...fileCache.keys()])
|
|
420
|
+
if (k.split(CFG_SEP)[0] === target)
|
|
421
|
+
fileCache.delete(k);
|
|
422
|
+
}
|
|
423
|
+
export function describeVerdict(v) {
|
|
424
|
+
const bits = [`${v.kind}:${v.encoding}`];
|
|
425
|
+
if (v.ambiguous)
|
|
426
|
+
bits.push(`候选=${v.candidates.join(">") || "多"}`);
|
|
427
|
+
if (v.hasFffd)
|
|
428
|
+
bits.push("含U+FFFD");
|
|
429
|
+
return bits.join(" ");
|
|
430
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Common Han characters used to tell a correct CJK decoding from mojibake when several legacy encodings
|
|
2
|
+
// round-trip the same bytes (for example a Big5 file that also decodes and re-encodes as GBK). Real text
|
|
3
|
+
// hits these sets heavily; mis-decoded bytes land on rare ideographs, kana rows or symbols instead.
|
|
4
|
+
//
|
|
5
|
+
// COMMON_HAN is derived from the codecs themselves at load time: GB2312 Level 1 (rows 0xB0-0xD7) is the
|
|
6
|
+
// standard set of 3,755 common simplified characters and the Big5 rows 0xA4-0xC6 hold the 5,401 most common
|
|
7
|
+
// traditional ones. Both families look "common" for the same bytes, so the decision rests on TOP_HAN: the
|
|
8
|
+
// most frequent characters of each script, which mojibake almost never produces. Kana and Hangul are scored
|
|
9
|
+
// as scripts and deliberately absent here.
|
|
10
|
+
import iconv from "iconv-lite";
|
|
11
|
+
function decodeRange(firstLead, lastLead, firstTrail, lastTrail, lastLeadTrailEnd, encoding) {
|
|
12
|
+
// Batch all 2-byte pairs into one buffer so iconv.decode runs once per table instead of ~12,000 times at import.
|
|
13
|
+
const bytes = [];
|
|
14
|
+
for (let lead = firstLead; lead <= lastLead; lead++) {
|
|
15
|
+
const trailEnd = lead === lastLead ? lastLeadTrailEnd : lastTrail;
|
|
16
|
+
for (let trail = firstTrail; trail <= trailEnd; trail++) {
|
|
17
|
+
if (encoding === "Big5" && trail >= 0x80 && trail <= 0xa0)
|
|
18
|
+
continue;
|
|
19
|
+
bytes.push(lead, trail);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const out = [];
|
|
23
|
+
for (const ch of iconv.decode(Buffer.from(bytes), encoding)) {
|
|
24
|
+
if (ch !== "\ufffd")
|
|
25
|
+
out.push(ch);
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
let _commonHan = null;
|
|
30
|
+
/** Lazily built set of common GB2312 Level-1 + Big5 Han characters; zero cost for pure UTF-8/ASCII files. */
|
|
31
|
+
export function getCommonHan() {
|
|
32
|
+
if (!_commonHan) {
|
|
33
|
+
_commonHan = new Set([
|
|
34
|
+
...decodeRange(0xb0, 0xd7, 0xa1, 0xfe, 0xf9, "GB2312"),
|
|
35
|
+
...decodeRange(0xa4, 0xc6, 0x40, 0xfe, 0x7e, "Big5"),
|
|
36
|
+
]);
|
|
37
|
+
}
|
|
38
|
+
return _commonHan;
|
|
39
|
+
}
|
|
40
|
+
export const TOP_HAN = new Set(Array.from(
|
|
41
|
+
// Frequent simplified characters: function words, pronouns, time, common verbs and nouns.
|
|
42
|
+
"的一是不了在人有我他这个们中来上大为和国地到以说时要就出会可也你对生能而子那得于着下自之年过发后作里用道行所然家种事成方多经么去法学如都同现当没动面起看定天分还进好小部其些主样理心她本前开但因只从想实日军者意无力它与长把机十民第公此已工使情明性知全三又关点正业外将两高间由问很最重并物手应战向头文体政美相见被利什二等产或新己制身果加西斯月话合回特代内信表化老给世位次度门任常先海通教儿原东声提立及比员解水名真论处走义各入几口认条平系气题活尔更别打女变四总才电金何反士受且路见程影红放强即像难觉边" +
|
|
43
|
+
// Surnames, which dense Chinese prose is full of.
|
|
44
|
+
"王李张刘陈杨黄赵吴周徐孙马朱胡郭何高林罗郑梁谢宋唐许韩冯邓曹彭曾肖田董袁潘于蒋蔡余杜叶程苏魏吕丁任沈姚卢姜崔钟谭陆汪范金石廖贾夏韦付方白邹孟熊秦邱江尹薛闫段雷侯龙史陶黎贺顾毛郝龚邵万钱严覃武戴莫孔向汤常温康施文屈鲁倪庄" +
|
|
45
|
+
// Technical and business vocabulary.
|
|
46
|
+
"文件数据程序代码系统网络服务器软件硬件内存磁盘目录路径配置设置选项参数变量函数返回结果编译运行调试测试错误警告信息内容格式结构类型数值大小长度宽度高度位置方向速度周期频率电压电流温度压力功率马达电机电源开关控制输入输出显示隐藏加载保存读取写入删除修改查询添加创建销毁释放分配管理用户密码账号登录退出注册邮箱地址电话号码名称标题描述备注标签颜色状态开始结束暂停继续成功失败完成进行准备执行处理转换编解码压缩加解密签名验证授权权限角色菜单按钮链接图片视频音频播放停止启动关闭打开编辑查看搜索过滤排序分组统计计算比较判断循环条件分支默认空值真假日志记录跟踪监控通知消息发送接收请求响应服务客户端主机端口协议安全证书密钥" +
|
|
47
|
+
// Traditional forms of the same vocabulary.
|
|
48
|
+
"的一是不了在人有我他這個們中來上大為和國地到以說時要就出會可也你對生能而子那得於著下自之年過發後作裡用道行所然家種事成方多經麼去法學如都同現當沒動面起看定天分還進好小部其些主樣理心她本前開但因只從想實日軍者意無力它與長把機十民第公此已工使情明性知全三又關點正業外將兩高間由問很最重並物手應戰向頭文體政美相見被利什二等產或新己制身果加西斯月話合回特代內信表化老給世位次度門任常先海通教兒原東聲提立及比員解水名真論處走義各入幾口認條平系氣題活爾更別打女變四總才電金何反士受且路見程影紅放強即像難覺邊" +
|
|
49
|
+
"王李張劉陳楊黃趙吳周徐孫馬朱胡郭何高林羅鄭梁謝宋唐許韓馮鄧曹彭曾肖田董袁潘于蔣蔡余杜葉程蘇魏呂丁任沈姚盧姜崔鍾譚陸汪范金石廖賈夏韋付方白鄒孟熊秦邱江尹薛閆段雷侯龍史陶黎賀顧毛郝龔邵萬錢嚴覃武戴莫孔向湯常溫康施文屈魯倪莊" +
|
|
50
|
+
"檔案數據程式代碼系統網路伺服器軟體硬體記憶體磁碟目錄路徑配置設定選項參數變數函數回傳結果編譯執行除錯測試錯誤警告資訊內容格式結構類型數值大小長度寬度高度位置方向速度週期頻率電壓電流溫度壓力功率馬達電機電源開關控制輸入輸出顯示隱藏載入儲存讀取寫入刪除修改查詢新增建立銷毀釋放分配管理使用者密碼帳號登入登出註冊電子郵件地址電話號碼名稱標題描述備註標籤顏色狀態開始結束暫停繼續成功失敗完成進行準備執行處理轉換編解碼壓縮加解密簽章驗證授權權限角色選單按鈕連結圖片視訊音訊播放停止啟動關閉開啟編輯檢視搜尋篩選排序分組統計計算比較判斷迴圈條件分支預設空值真假記錄追蹤監控警告通知訊息傳送接收請求回應服務用戶端主機埠協定安全憑證金鑰"));
|
|
51
|
+
// Frequent Japanese kanji. GB2312 carries the same kana rows as JIS, so a EUC-JP or Shift_JIS file read as
|
|
52
|
+
// GBK shows correct kana next to mojibake kanji; whether the kanji themselves are common Japanese words is
|
|
53
|
+
// what separates the two readings.
|
|
54
|
+
export const JP_KANJI = new Set(Array.from("日一国会人年大十二本中長出三同時政事自行社見月分議後前民生連五発間対上部東者党地合市業内相方四定今回新場金員九入選立開手米力学問高代明実円関決子動京全目表戦経通外最言氏現理調体化田当八六約主題下首意法不来作性的要用制治度務強気小七成期公持野協取都和統以機平総加山思家話世受区領多県続進正安設保改数記院女初北午指権心界支第産結百派点教報済書府活原先共得解名交資予川向際査勝面委告軍文反元重近千考判認画海参売利組知案道信策集在件団別物側任引使求所次水半品昨論計死官増係感特情投示変打男基私各始島直両朝革価式確村提運終挙果西勢減台広容必応演電歳住争談能無再位置企真流格有疑口過局少放税検藤町常校料沢裁状工建語球営空職証土与急止送援供可役構木割聞身費付施切由説転食比難防補車優夫研収断井何南石足違消境神番規術護展態導鮮備宅害配副算視条幹独警宮究育席輸訪楽起万着乗店述残想線率病農州武声質念待試族象銀域助労例衛然早張映限親額監環験追審商葉義伝働形景落欧担好退準賞訴辺造英被株頭技低毎医復仕去姿味負閣韓渡失移差衆個門写評課末守若脳極種美岡影命含福蔵量望松非撃佐核観察整段横融型白深字答夜製票況音申様財港識注呼渉達良響阪帰針専推谷古候史天階程満敗管値歌買突兵接請器士光討路悪科攻崎督授催細効図週積丸他及湾録処省旧室憲太橋歩離岸客風紙激否周師摘材登系批郎母易健黒火戸速存花春飛殺央券赤号単盟座青破編捜竹除完降超責並療従右修捕隊危採織森競拡故館振給屋介読弁根色友苦就迎走販園具左異歴辞将秋因献厳馬愛幅休維富浜父遺彼般未塁貿講邦舞林装諸夏素亡劇河遣航抗冷模雪走害輪恋矢並童格拠余伊抽欲疲君欠"));
|
|
55
|
+
// Frequent Hangul syllables. Real Korean is highly skewed towards these; byte noise that happens to map
|
|
56
|
+
// into the Hangul block hits them rarely, which tells a real EUC-KR decode from GBK bytes read as EUC-KR
|
|
57
|
+
// (the GB2312 Level-1 hanzi rows overlap the KS X 1001 Hangul rows exactly).
|
|
58
|
+
export const COMMON_HANGUL = new Set(Array.from("가각간갈감갑강개거건걸검것게격견결경계고곡곤골공과관광교구국군굴권그근금급기긴길까지끝나난날남납내너넣녀년노논놓누는능니다단달담답당대더데도독동되된두들등디따때라락란랄략려로루르를리마만말망매머먹메명모목몰못무문물미바박반받발백배버번벌법베본볼봄부북분불비빈사산살삼상새색생서석선설성세소속손솔송수숙순술쓰시식신실심십싱아안않알암압앙애야약양어언얼업없에여역연열엽영예오온올옴와완왕외요용우운울워원월위유은을음응의이인일임입있자작잔잖잘잡장재저적전점접정제조존종좌주준줄중즉지진질집짓차찬창채책처천철첫체초최추축출충취치친칠침카커컴코콜쿠크클키타탁탄탈태택터토통투특파판팔패퍼편평포표풍프픔필하학한할함합항해핵행허험현혈형호혹홀화확환활황회획후훈휘휴흐흔희히힘"));
|