Read an .ics file

Parse an iCalendar file a person picks or uploads, report its problems with their lines, and turn its dates into instants.

A person exports a calendar from Google Calendar or Outlook and gives your app the .ics file. This page reads it in the browser, tells the person what the file got wrong, and checks an upload on a server. Nothing here needs the calendar or a UI framework.

Read the file

readIcsFile takes the File from an <input type="file"> or a drop, and the viewer's time zone. It returns the events with their times as instants, and a line for each problem:

read-ics-file.ts
import { getEventEnd, parseIcs, type IcsDateValue, type IcsIssue } from "@moltenship/ics";

export interface ImportedEvent {
  readonly id: string;
  readonly title: string;
  readonly allDay: boolean;
  readonly start: Temporal.Instant;
  readonly end: Temporal.Instant;
}

export interface ImportResult {
  readonly events: readonly ImportedEvent[];
  /** What to tell the person about the file, one line per problem. */
  readonly problems: readonly string[];
}

export async function readIcsFile(file: File, viewerTimeZone: string): Promise<ImportResult> {
  // `File.text()` decodes the bytes as UTF-8, the encoding iCalendar files use.
  const { calendars, issues } = parseIcs(await file.text());

  const events = calendars.flatMap((calendar) => {
    // Times without a zone are read in the file's X-WR-TIMEZONE, else in the viewer's zone.
    const timeZone = calendar.timeZone ?? viewerTimeZone;
    return calendar.events.map((event) => ({
      id: event.uid,
      title: event.summary ?? "Untitled",
      allDay: event.start.kind === "date",
      start: toInstant(event.start, timeZone),
      end: toInstant(getEventEnd(event), timeZone),
    }));
  });

  return { events, problems: issues.filter(isError).map(describe) };
}

parseIcs takes a string, not bytes. File.text() decodes the file as UTF-8, which is the encoding RFC 5545 names as the default. Read a Response with response.text(), and other bytes with new TextDecoder().decode(bytes).

A file can hold more than one VCALENDAR, so the function reads every calendar in calendars.

Turn dates into instants

An ICS start is one of five shapes, and kind says which. Two of them are instants already. The other three need a time zone, which you choose:

read-ics-file.ts
function toInstant(value: IcsDateValue, timeZone: string): Temporal.Instant {
  switch (value.kind) {
    case "utc":
      return value.instant;
    case "zoned":
      return value.zoned.toInstant();
    case "date":
      // An all-day event starts when its date starts in the chosen zone.
      return value.date.toZonedDateTime(timeZone).toInstant();
    case "floating":
    case "unresolved":
      return value.wallTime.toZonedDateTime(timeZone).toInstant();
  }
}
kindThe file wroteHow the function reads it
utcA time in UTC, ending in ZThe instant itself
zonedA time with a TZID the parser knowsThe instant in that zone
dateA date, for an all-day eventThe start of that date in the zone you chose
floatingA time with no zoneThat wall time in the zone you chose
unresolvedA time with a TZID nobody knowsThat wall time in the zone you chose

The parser never falls back to the host's time zone, so the choice is in your code. This function uses the calendar's X-WR-TIMEZONE, which Google Calendar writes, and the viewer's zone when the file has none. Time zones lists how a TZID is resolved, Outlook's Windows names included.

getEventEnd returns the end in the start's kind: the file's DTEND, or the start plus DURATION. An event with neither ends the next day when it's all-day, and when it starts when it's timed, so give such an event a length of your own before you show it.

An all-day event keeps its date in event.start.date. Keep that Temporal.PlainDate instead of an instant if your app shows all-day events on a date, as the calendar does.

Tell the person what went wrong

The parser is lenient. It keeps every event it can read and lists what it couldn't in issues. An issue with the severity "error" dropped a value or a whole component, and one with "warning" kept a value read leniently. Each has the line it came from, when it came from one:

read-ics-file.ts
function isError(issue: IcsIssue): boolean {
  return issue.severity === "error";
}

function describe(issue: IcsIssue): string {
  return issue.line === undefined ? issue.message : `Line ${issue.line}: ${issue.message}`;
}

For a file whose second event has no DTSTART, problems holds one line, and events holds the other events:

Line 9: VEVENT has no DTSTART; skipped

Issues and strict mode lists every code.

Refuse a file with errors

To import all of a file or none of it, parse with strict: true. The parser then throws an IcsParseError when the text has an error. Its message is the first error's, with a count of the others, and its issues lists them all. Warnings never throw:

read-strictly.ts
import { IcsParseError } from "@moltenship/ics";

/** The file's calendars, or the reason the file is refused. */
export function readStrictly(text: string) {
  try {
    return { ok: true as const, calendars: parseIcs(text, { strict: true }).calendars };
  } catch (error) {
    if (!(error instanceof IcsParseError)) throw error;
    return { ok: false as const, reason: error.message, issues: error.issues };
  }
}

Text without a VCALENDAR is an error too, so this also refuses a file that isn't a calendar.

Check an upload on a server

A parser is a Standard Schema: its validate fails with the errors, or succeeds with the parse result. A value that isn't a string fails as well, so a form without a file gets the same answer as a bad file. This handler runs wherever Request and Response do:

route.ts
import { createIcsParser } from "@moltenship/ics";

const parser = createIcsParser();

/** A route handler for a form with an `<input type="file" name="calendar">`. */
export async function POST(request: Request): Promise<Response> {
  const file = (await request.formData()).get("calendar");
  const body = file instanceof File ? await file.text() : undefined;

  // A parser is a Standard Schema: it fails with the errors, or succeeds with the result.
  const result = await parser["~standard"].validate(body);
  if (result.issues) {
    return Response.json({ errors: result.issues.map((issue) => issue.message) }, { status: 400 });
  }

  const events = result.value.calendars.flatMap((calendar) => calendar.events);
  return Response.json({ imported: events.length });
}

Anything that takes a Standard Schema takes the parser the same way, such as a form library or a router's body validation.

Recurring events

A recurring event arrives as one event with a recurrenceRule, and each changed occurrence as another event with the same uid and a recurrenceId. So uid alone doesn't identify an event in a file with series. @moltenship/calendar-recurrence groups such events into series with recurringEventsFromIcs and lists their occurrences for a range of dates.

On this page