diff --git a/components/vault/useVaultImportHandlers.ts b/components/vault/useVaultImportHandlers.ts index a5049daec..85feddba7 100644 --- a/components/vault/useVaultImportHandlers.ts +++ b/components/vault/useVaultImportHandlers.ts @@ -46,7 +46,9 @@ export function useVaultImportHandlers({ toast.info(t("vault.import.toast.start", { format: formatLabel })); - const text = await readTextFile(file); + const text = await readTextFile(file, { + fallbackEncoding: format === "mobaxterm" ? "gb18030" : undefined, + }); const result = importVaultHostsFromText(format, text, { fileName: file.name, }); diff --git a/lib/readTextFile.test.ts b/lib/readTextFile.test.ts index 199744d05..00845f1c5 100644 --- a/lib/readTextFile.test.ts +++ b/lib/readTextFile.test.ts @@ -24,3 +24,27 @@ test("readTextFile decodes UTF-16 BE with BOM", async () => { const file = new File([bytes], "note.md", { type: "text/plain" }); assert.equal(await readTextFile(file), "hi"); }); + +test("readTextFile uses the fallback encoding for non-UTF-8 text without a BOM", async () => { + const bytes = new Uint8Array([ + 0x5b, 0x42, 0x6f, 0x6f, 0x6b, 0x6d, 0x61, 0x72, 0x6b, 0x73, 0x5d, 0x0a, + 0xd6, 0xd0, 0xce, 0xc4, 0xb7, 0xfe, 0xce, 0xf1, 0xc6, 0xf7, + ]); + const file = new File([bytes], "MobaXterm.ini", { type: "text/plain" }); + + assert.equal( + await readTextFile(file, { fallbackEncoding: "gb18030" }), + "[Bookmarks]\n中文服务器", + ); +}); + +test("readTextFile keeps valid UTF-8 when a fallback encoding is configured", async () => { + const file = new File(["[Bookmarks]\n中文服务器"], "MobaXterm.ini", { + type: "text/plain", + }); + + assert.equal( + await readTextFile(file, { fallbackEncoding: "gb18030" }), + "[Bookmarks]\n中文服务器", + ); +}); diff --git a/lib/readTextFile.ts b/lib/readTextFile.ts index 1b103e01f..0c032e306 100644 --- a/lib/readTextFile.ts +++ b/lib/readTextFile.ts @@ -1,4 +1,11 @@ -export async function readTextFile(file: File): Promise { +type ReadTextFileOptions = { + fallbackEncoding?: string; +}; + +export async function readTextFile( + file: File, + options: ReadTextFileOptions = {}, +): Promise { const buf = await file.arrayBuffer(); const bytes = new Uint8Array(buf); @@ -21,6 +28,14 @@ export async function readTextFile(file: File): Promise { offset = 3; } - const decoder = new TextDecoder(encoding); - return decoder.decode(bytes.slice(offset)); + const content = bytes.slice(offset); + if (offset === 0 && options.fallbackEncoding) { + try { + return new TextDecoder("utf-8", { fatal: true }).decode(content); + } catch { + return new TextDecoder(options.fallbackEncoding).decode(content); + } + } + + return new TextDecoder(encoding).decode(content); }