import { documentHasRecurrence, parseProperty, recurrenceBase } from "@/worker/caldav/ical/core"; import { parseCalendarDocument } from "@/worker/caldav/ical/parse"; import { calendarOccurrences, occurrenceOverlaps } from "@/worker/caldav/ical/recurrence"; import type { CalendarOccurrence, CalendarTimeRange, RecurrenceBounds } from "@/worker/caldav/ical/types"; function formatUtcDate(ms: number): string { const date = new Date(ms); const pad = (value: number) => String(value).padStart(2, "0"); return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}`; } function formatUtcDateTime(ms: number): string { const date = new Date(ms); const pad = (value: number) => String(value).padStart(2, "0"); return `${formatUtcDate(ms)}T${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`; } function datePropertyLine(name: string, ms: number, valueType: "date" | "date-time"): string { return valueType === "date" ? `${name};VALUE=DATE:${formatUtcDate(ms)}` : `${name}:${formatUtcDateTime(ms)}`; } function expandedComponent(occurrence: CalendarOccurrence, forceRecurrenceId: boolean): string[] { const excluded = new Set(["DTSTART", "DTEND", "DUE", "DURATION", "RRULE", "RDATE", "EXDATE", "RECURRENCE-ID"]); const preserved = occurrence.component.lines.filter((line) => { const prop = parseProperty(line); return prop && !excluded.has(prop.name); }); const lines = [`BEGIN:${occurrence.component.componentType}`, ...preserved]; const recurrenceValueType = occurrence.component.recurrenceId?.valueType ?? recurrenceBase(occurrence.component)?.valueType ?? "date-time"; const startValueType = occurrence.component.dtstart?.valueType ?? recurrenceBase(occurrence.component)?.valueType ?? "date-time"; if (forceRecurrenceId || !occurrence.isInitial || occurrence.component.recurrenceId) { lines.push(datePropertyLine("RECURRENCE-ID", occurrence.originalStartMs, recurrenceValueType)); } lines.push(datePropertyLine("DTSTART", occurrence.startMs, startValueType)); if (occurrence.component.componentType === "VEVENT") { if (occurrence.endMs !== occurrence.startMs) lines.push(datePropertyLine("DTEND", occurrence.endMs, startValueType)); } else if (occurrence.component.componentType === "VTODO") { lines.push(datePropertyLine("DUE", occurrence.endMs, startValueType)); } lines.push(`END:${occurrence.component.componentType}`); return lines; } export function expandCalendarData(body: string, range: CalendarTimeRange, bounds: RecurrenceBounds): string { const document = parseCalendarDocument(body); const lines = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//dab//CalDAV//EN"]; const forceRecurrenceId = documentHasRecurrence(document.components) && document.overrides.length === 0; for (const occurrence of calendarOccurrences(document, bounds, range)) { if (occurrenceOverlaps(document, occurrence, range)) { lines.push(...expandedComponent(occurrence, forceRecurrenceId)); } } lines.push("END:VCALENDAR", ""); return lines.join("\r\n"); }