dist / fileSearch / web / encoding.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeEncoding = normalizeEncoding;
exports.encodingForFile = encodingForFile;
exports.encodingPreferencesForMessages = encodingPreferencesForMessages;
exports.encodingForMessages = encodingForMessages;
exports.decodeDocument = decodeDocument;
const cheerio_1 = require("cheerio");
const hint = 'Use @file-encoding auto, utf-8, utf-16le, utf-16be or sjis on its own line; optionally add a filename, e.g. @file-encoding sjis "page.html".';
function normalizeEncoding(label) {
const value = label.trim().toLowerCase();
if (value === "auto")
return value;
// Node's TextDecoder recognizes windows-31j but not the common CP932 label.
if (["cp932", "windows-932"].includes(value))
return "shift_jis";
try {
const encoding = new TextDecoder(value).encoding;
if (["utf-8", "utf-16le", "utf-16be", "shift_jis"].includes(encoding))
return encoding;
}
catch { /* Report the same actionable error for unknown/unsupported labels. */ }
throw new Error(`Unsupported document encoding: ${label}. ${hint}`);
}
function encodingForFile(preferences, name) {
return preferences.overrides.get(name) ?? preferences.defaultEncoding;
}
function encodingPreferencesForMessages(messages) {
const preferences = { defaultEncoding: "auto", overrides: new Map() };
for (const message of messages) {
if (!message.isUserMessage())
continue;
let fence;
for (const line of message.getText().split(/\r?\n/)) {
const delimiter = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
if (delimiter) {
if (!fence)
fence = delimiter;
else if (delimiter[0] === fence[0] && delimiter.length >= fence.length)
fence = undefined;
continue;
}
if (fence || !/^\s*@file-encoding(?:\s|$)/i.test(line))
continue;
const match = /^\s*@file-encoding\s+(\S+)(?:\s+(.+?))?\s*$/i.exec(line);
if (!match)
throw new Error(hint);
const encoding = normalizeEncoding(match[1]);
let name = match[2]?.trim();
if (name?.startsWith('"')) {
try {
name = JSON.parse(name);
}
catch {
throw new Error(hint);
}
}
if (name !== undefined) {
if (typeof name !== "string" || !name.trim() || name.length > 512)
throw new Error(hint);
preferences.overrides.set(name, encoding);
}
else
preferences.defaultEncoding = encoding;
}
}
return preferences;
}
function encodingForMessages(messages) {
return encodingPreferencesForMessages(messages).defaultEncoding;
}
function declaredHtmlEncoding(bytes) {
// Read ASCII markup without first decoding its Japanese body. Parsing avoids
// mistaking meta-like text in comments/scripts for an actual declaration.
const $ = (0, cheerio_1.load)(bytes.subarray(0, 64 * 1024).toString("latin1"));
for (const el of $("meta").toArray()) {
const meta = $(el);
let label = meta.attr("charset")?.trim();
if (!label && meta.attr("http-equiv")?.toLowerCase() === "content-type") {
label = /(?:^|;)\s*charset\s*=\s*["']?([^\s;"']+)/i.exec(meta.attr("content") ?? "")?.[1];
}
if (label) {
const encoding = normalizeEncoding(label);
if (encoding === "auto")
throw new Error(`Invalid HTML charset: auto. ${hint}`);
return encoding;
}
}
return undefined;
}
function decodeDocument(name, bytes, override = "auto") {
const manual = normalizeEncoding(override);
const decode = (encoding, encodingSource) => {
try {
return { text: new TextDecoder(encoding, { fatal: true }).decode(bytes), encoding, encodingSource };
}
catch {
throw new Error(`Cannot decode ${name} as ${encoding} (${encodingSource}). ${hint}`);
}
};
if (manual !== "auto")
return decode(manual, "manual");
if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)
return decode("utf-8", "bom");
if (bytes[0] === 0xff && bytes[1] === 0xfe)
return decode("utf-16le", "bom");
if (bytes[0] === 0xfe && bytes[1] === 0xff)
return decode("utf-16be", "bom");
if (/\.html?$/i.test(name)) {
const declared = declaredHtmlEncoding(bytes);
if (declared && declared !== "auto")
return decode(declared, "html-meta");
}
try {
return decode("utf-8", "utf8");
}
catch {
return decode("shift_jis", "sjis-fallback");
}
}