// Zeichensatz von Importdateien erkennen: GAEB-XML nennt ihn in der ersten Zeile, DATANORM ist meist im alten // DOS-Zeichensatz (Codepage 850), manchmal Windows-1252 oder UTF-8. Codepage 850 kennt TextDecoder nicht. const CP850 = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "; export function cp850(bytes: Uint8Array): string { let s = ""; for (let i = 0; i < bytes.length; i += 8192) { const teil = bytes.subarray(i, i + 8192); s += Array.from(teil, (b) => (b < 128 ? String.fromCharCode(b) : CP850[b - 128]!)).join(""); } return s; } function utf8(bytes: Uint8Array): string | null { try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch { return null; } } /** Text einer Datei: UTF-8, sonst Codepage 850 oder Windows-1252, je nachdem, wo Umlaute plausibler sind */ export function dateiText(bytes: Uint8Array): string { // GAEB-XML: Kodierung aus der XML-Deklaration const anfang = new TextDecoder("latin1").decode(bytes.subarray(0, 200)); const dekl = /<\?xml[^>]*encoding=["']([^"']+)["']/i.exec(anfang); if (dekl) { const k = dekl[1]!.toLowerCase(); if (k === "utf-8" || k === "utf8") return utf8(bytes) ?? new TextDecoder("windows-1252").decode(bytes); try { return new TextDecoder(k).decode(bytes); } catch { /* unbekannt: raten */ } } const u = utf8(bytes); if (u !== null) return u.replace(/^/, ""); let dos = 0, win = 0; for (const b of bytes) { if (b === 0x81 || b === 0x84 || b === 0x94 || b === 0x8e || b === 0x99 || b === 0x9a || b === 0xe1) dos++; else if (b === 0xe4 || b === 0xf6 || b === 0xfc || b === 0xc4 || b === 0xd6 || b === 0xdc || b === 0xdf) win++; } return dos > win ? cp850(bytes) : new TextDecoder("windows-1252").decode(bytes); }