import { BERLIN_VTIMEZONE_LINES, toBerlinICSDateTime, toUTCICSStamp } from "./timezone"; export type ICSEvent = { uid: string; start: Date; end: Date; summary: string; description?: string; location?: string; url?: string; }; function escapeICSText(value: string): string { return value .replace(/\\/g, "\\\\") .replace(/;/g, "\\;") .replace(/,/g, "\\,") .replace(/\n/g, "\\n"); } /** RFC 5545 line folding: lines must not exceed 75 octets; continuations start with a single space. */ function foldLine(line: string): string { const encoder = new TextEncoder(); if (encoder.encode(line).length <= 75) return line; const chunks: string[] = []; let current = ""; for (const char of line) { const candidate = current + char; if (encoder.encode(candidate).length > 75) { chunks.push(current); current = char; } else { current = candidate; } } if (current) chunks.push(current); return chunks.join("\r\n "); } /** Builds a complete RFC 5545 VCALENDAR document, Europe/Berlin timezone-aware throughout. */ export function buildICSCalendar(args: { calendarName: string; events: ICSEvent[] }): string { const lines: string[] = [ "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//ANOUMA//Calendar Feed//DE", "CALSCALE:GREGORIAN", "METHOD:PUBLISH", `X-WR-CALNAME:${escapeICSText(args.calendarName)}`, "X-WR-TIMEZONE:Europe/Berlin", ...BERLIN_VTIMEZONE_LINES, ]; const stamp = toUTCICSStamp(new Date()); for (const ev of args.events) { lines.push( "BEGIN:VEVENT", `UID:${ev.uid}`, `DTSTAMP:${stamp}`, `DTSTART;TZID=Europe/Berlin:${toBerlinICSDateTime(ev.start)}`, `DTEND;TZID=Europe/Berlin:${toBerlinICSDateTime(ev.end)}`, `SUMMARY:${escapeICSText(ev.summary)}`, ); if (ev.description) lines.push(`DESCRIPTION:${escapeICSText(ev.description)}`); if (ev.location) lines.push(`LOCATION:${escapeICSText(ev.location)}`); if (ev.url) lines.push(`URL:${ev.url}`); lines.push("STATUS:CONFIRMED", "END:VEVENT"); } lines.push("END:VCALENDAR"); return lines.map(foldLine).join("\r\n") + "\r\n"; }