/**
* A fetched page's bytes as text, by the charset it declares (the critique's must_change, 9 Nov
* 2026). Pure: no Deno, no network.
*/
/**
* The charset a page declares: its Content-Type's `charset=`, else a or a
* in its first 4,096 bytes (read as Latin-1, which keeps every
* ASCII byte). Null when it declares none.
*/
export function declaredCharset(bytes: Uint8Array, contentType: string | null): string | null {
const fromHeader = /charset\s*=\s*["']?([\w.:-]+)/i.exec(contentType ?? '');
if (fromHeader) return fromHeader[1].toLowerCase();
const head = new TextDecoder('latin1').decode(bytes.subarray(0, 4096));
const meta =
/]+charset\s*=\s*["']?\s*([\w.:-]+)/i.exec(head) ??
/]+content\s*=\s*["'][^"']*charset\s*=\s*([\w.:-]+)/i.exec(head);
return meta ? meta[1].toLowerCase() : null;
}
/**
* A page's bytes as text, by the charset it declares (the critique's must_change, 9 Nov 2026: a
* Korean agency's notice in EUC-KR, a Japanese page in Shift_JIS, a regulator's in Windows-1252
* came in garbled through res.text(), which always reads UTF-8). A byte-order mark wins, then
* the header, then the page's own meta; UTF-8 when it declares none or a charset the runtime does
* not know. Pure.
*/
export function decodePage(bytes: Uint8Array, contentType: string | null): string {
if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)
return new TextDecoder('utf-8').decode(bytes.subarray(3));
if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder('utf-16le').decode(bytes);
if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder('utf-16be').decode(bytes);
const label = declaredCharset(bytes, contentType);
if (label && label !== 'utf-8' && label !== 'utf8') {
try {
return new TextDecoder(label).decode(bytes);
} catch {
// A label the runtime does not know: read as UTF-8, as before.
}
}
return new TextDecoder('utf-8').decode(bytes);
}