diff --git a/src/converters/vcf.ts b/src/converters/vcf.ts index d84094c0..8b1a9b99 100644 --- a/src/converters/vcf.ts +++ b/src/converters/vcf.ts @@ -9,6 +9,32 @@ export const properties = { }, }; +// Undo vCard text escapes: \, \; \\ and \n +const unescape = (value: string) => + value.replace(/\\([,;\\nN])/g, (_, c) => (c === "n" || c === "N" ? "\n" : c)); + +// Split a structured value (N, ORG) on the ";" separators, not on escaped "\;" (but on "\\;") +const splitFields = (value: string) => value.split(/(?<=(?:^|[^\\])(?:\\\\)*);/); + +// vCard 2.1 parameters: "ENCODING=QUOTED-PRINTABLE" or a bare "QUOTED-PRINTABLE" +const isQuotedPrintable = (params: string[]) => + params.some((param) => /^(ENCODING=)?QUOTED-PRINTABLE$/i.test(param)); + +// vCard 2.1 exports (Android) write non-ASCII values as quoted-printable bytes in CHARSET +const decodeQuotedPrintable = (value: string, params: string[]) => { + const bytes = Buffer.from( + value.replace(/=([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))), + "latin1", + ); + const charset = (params.find((param) => /^CHARSET=/i.test(param))?.slice(8) || + "utf-8") as ConstructorParameters[0]; + try { + return new TextDecoder(charset).decode(bytes); + } catch { + return bytes.toString("utf-8"); + } +}; + export function parseVCF(data: string): Record[] { const cards = data .split(/BEGIN:VCARD/) @@ -18,25 +44,50 @@ export function parseVCF(data: string): Record[] { return cards .map((card) => { if (!card) return {}; - const lines = card.split("\n").filter((line) => line.trim()); + const lines: string[] = []; + for (const raw of card.split("\n")) { + const line = raw.replace(/\r$/, ""); + const prev = lines[lines.length - 1]; + if (prev !== undefined && /^[ \t]/.test(line)) { + // a folded line continues the previous one after its leading space + lines[lines.length - 1] = prev + line.slice(1); + } else if ( + prev?.endsWith("=") && + isQuotedPrintable((prev.split(":")[0] || "").split(";")) + ) { + // a quoted-printable value ending in "=" continues on the next line + lines[lines.length - 1] = prev.slice(0, -1) + line; + } else if (line.trim()) { + lines.push(line); + } + } const contact: Record = {}; + const add = (field: string, value: string) => { + if (value) contact[field] = contact[field] ? `${contact[field]}; ${value}` : value; + }; for (const line of lines) { const colonIndex = line.indexOf(":"); if (colonIndex === -1) continue; - const key = line.slice(0, colonIndex).trim(); + // "item1.EMAIL;type=INTERNET" -> name EMAIL, params type=INTERNET + const [property = "", ...rawParams] = line.slice(0, colonIndex).trim().split(";"); + const params = rawParams.map((param) => param.replace(/"/g, "")); + const key = property.replace(/^[^.]*\./, "").toUpperCase(); const value = line.slice(colonIndex + 1).trim(); + // decode each field after splitting, so an encoded "=3B" is not a separator + const decode = (field = "") => + unescape(isQuotedPrintable(params) ? decodeQuotedPrintable(field, params) : field); if (key === "FN") { - contact["Full Name"] = value; + contact["Full Name"] = decode(value); } else if (key === "N") { - const parts = value.split(";"); - contact["Last Name"] = parts[0] || ""; - contact["First Name"] = parts[1] || ""; - } else if (key.startsWith("TEL")) { - contact["Phone"] = value; - } else if (key.startsWith("EMAIL")) { - contact["Email"] = value; + const parts = splitFields(value); + contact["Last Name"] = decode(parts[0]); + contact["First Name"] = decode(parts[1]); + } else if (key === "TEL") { + add("Phone", decode(value)); + } else if (key === "EMAIL") { + add("Email", decode(value)); } else if (key === "ORG") { - contact["Organization"] = value.split(";")[0] || ""; + contact["Organization"] = decode(splitFields(value)[0]); } } return contact; diff --git a/tests/converters/vcf.test.ts b/tests/converters/vcf.test.ts index d6bf2412..a0fd8e90 100644 --- a/tests/converters/vcf.test.ts +++ b/tests/converters/vcf.test.ts @@ -66,6 +66,93 @@ END:VCARD`; ]); }); + test("should keep every phone and email, including grouped ones", () => { + const vcfData = [ + "BEGIN:VCARD", + "VERSION:3.0", + "FN:John Appleseed", + "ORG:Acme\\, Inc.;", + "item1.EMAIL;type=INTERNET;type=pref:john@example.com", + "item1.X-ABLabel:_$!!$_", + "TEL;type=CELL;type=pref:+1 555 123 4567", + "PHOTO;ENCODING=b;TYPE=JPEG:/9j/4AAQSkZJRg==", + "TEL;type=WORK:+1 555 987 6543", + "EMAIL;type=INTERNET;type=WORK:john@work.example", + "END:VCARD", + ].join("\r\n"); + + expect(parseVCF(vcfData)).toEqual([ + { + "Full Name": "John Appleseed", + Organization: "Acme, Inc.", + Email: "john@example.com; john@work.example", + Phone: "+1 555 123 4567; +1 555 987 6543", + }, + ]); + }); + + test("should decode quoted-printable names from vCard 2.1", () => { + const vcfData = [ + "BEGIN:VCARD", + "VERSION:2.1", + "N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:M=C3=BCller;J=C3=BCrgen;;;", + "FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:J=C3=BCrgen M=", + "=C3=BCller", + "END:VCARD", + ].join("\r\n"); + + expect(parseVCF(vcfData)).toEqual([ + { "Last Name": "Müller", "First Name": "Jürgen", "Full Name": "Jürgen Müller" }, + ]); + }); + + test("should unfold long lines and keep escaped semicolons", () => { + const vcfData = [ + "BEGIN:VCARD", + "VERSION:3.0", + "N:Doe\\;Smith;John;;;", + "FN:John Doe-Smith of the Very Long Name Department of the Company Papadimitrio", + " u Junior", + "ORG:R\\;D Labs;Research", + "END:VCARD", + ].join("\r\n"); + + expect(parseVCF(vcfData)).toEqual([ + { + "Last Name": "Doe;Smith", + "First Name": "John", + "Full Name": + "John Doe-Smith of the Very Long Name Department of the Company Papadimitriou Junior", + Organization: "R;D Labs", + }, + ]); + }); + + test("should split after an escaped backslash and decode fields after splitting", () => { + const vcfData = [ + "BEGIN:VCARD", + "VERSION:2.1", + "N:Doe\\\\;John;;;", + 'ORG;CHARSET=UTF-8;ENCODING="QUOTED-PRINTABLE":R=3BD Labs;Research', + "END:VCARD", + ].join("\r\n"); + + expect(parseVCF(vcfData)).toEqual([ + { "Last Name": "Doe\\", "First Name": "John", Organization: "R;D Labs" }, + ]); + }); + + test("should decode quoted-printable values in their charset", () => { + const vcfData = [ + "BEGIN:VCARD", + "VERSION:2.1", + "N;CHARSET=ISO-8859-1;QUOTED-PRINTABLE:M=FCller;J=FCrgen;;;", + "END:VCARD", + ].join("\r\n"); + + expect(parseVCF(vcfData)).toEqual([{ "Last Name": "Müller", "First Name": "Jürgen" }]); + }); + test("should handle CRLF line endings", () => { const vcfData = "BEGIN:VCARD\r\nFN:John Doe\r\nTEL:123\r\nEND:VCARD\r\n";