moon-ical

    iCalendar (RFC 5545) parsing, recurrence expansion, and a minimal CalDAV server in pure MoonBit

    icalendar
    calendar
    caldav
    rrule
    rfc5545
    Download zip
    Version
    0.6.0
    License
    Apache-2.0
    Last updated
    1 hour ago
    Downloads
    96

    #moon-ical

    A pure MoonBit iCalendar library with a minimal CalDAV server. It reads and writes component trees, calculates a defined subset of recurring events, and provides discovery and editing for stored calendar resources. It does not calculate every valid iCalendar input.

    #Version

    moon add justinwongcn/moon-ical@0.5.0

    0.5.0 is the published version (2026-10-31); it adds the RDATE sets, strict fixed time zones, and checked-query evaluation described below.

    #What it handles

    • Line unfolding, quoted parameters, TEXT escaping, and nested components. Unknown properties remain in the component tree and survive tree round trips.
    • UTC, floating times, all-day dates, and explicitly bound fixed-offset TZIDs. Unsupported time-zone definitions fail when a typed date references them.
    • DAILY, WEEKLY, MONTHLY, and YEARLY recurrence, with INTERVAL, COUNT, UNTIL, ordinal BYDAY, signed BYMONTHDAY, BYMONTH, BYSETPOS, and WKST.
    • DATE/DATE-TIME RDATE values, merged with recurrence slots and deduplicated. EXDATE removes instances; RECURRENCE-ID can move or cancel them; RANGE=THISANDFUTURE shifts later instances. DURATION supplies an end when DTEND is absent.
    • CRLF serialization, folding within 75 octets without splitting UTF-8, and parameter quoting.
    • A native server with vdir storage, content-addressed ETags, discovery, PROPFIND, calendar-query/multiget REPORT, MKCALENDAR, and conditional PUT/DELETE. The library also parses MKCALENDAR properties; the server does not persist them.

    Preserving a component tree is separate from interpreting its dates. For example, a tree containing PERIOD or dynamic VTIMEZONE data can be read and written by the library, while typed event parsing may reject it. The server applies that distinction at the door: a PUT body its evaluation cannot read is refused with 403 and the CALDAV:valid-calendar-data (or valid-calendar-object-resource) precondition, so stored content never poisons the collection's reports. Storage is also VEVENT-only, matching the supported-calendar-component-set the collection itself advertises: the iCalendar METHOD property and mixed entity types are refused with CALDAV:valid-calendar-object-resource (RFC 4791 §4.1), and a VTODO/VJOURNAL/VFREEBUSY body is refused with CALDAV:supported-calendar- component.

    #Library usage

    ///|
    test {
    let events = @moon-ical.parse_events(
    "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:demo\r\n" +
    "DTSTART:20260901T090000Z\r\nRRULE:FREQ=DAILY;COUNT=3\r\n" +
    "END:VEVENT\r\nEND:VCALENDAR\r\n",
    )
    let occurrences = @moon-ical.expand_series(events)
    assert_eq(occurrences.length(), 3)
    assert_eq(occurrences[2].start.to_string(), "2026-09-03T09:00:00Z")
    }

    The root package exports parse, recurrence, and serialization workflows. Lower-level APIs live in ical/text, ical/model, ical/rrule, ical/serialize, and ical/caldav. Since 0.2.0, the root facade no longer exports the low-level text and protocol helpers that 0.1.0 exposed.

    #0.5.0 calculation contract

    RDATE accepts DATE or DATE-TIME, including repeated lines and comma lists. PERIOD and mismatched value types are errors. Recurrence needs DTSTART; RDATE, RECURRENCE-ID, and override starts must use a compatible DATE/floating domain. RDATE values are independent of RRULE COUNT/UNTIL.

    limit budgets raw RRULE instances, not the size of the merged result: RDATE is included in full, while exclusions may shorten the result. expand and expand_series fail if the 10000-period safety budget ends before natural exhaustion or the requested instance budget is filled. For completeness information, import ical/rrule and use expand_series_query; its raw frontier excludes RDATE and is not enough to prove a moved override's query window complete.

    ZoneTable::builtin_common() now contains UTC/GMT/Z aliases only. Regional names no longer receive guessed standard offsets. Use UTC, a provably fixed VTIMEZONE, or an explicit ZoneTable::insert binding. An explicit binding means the caller is choosing a fixed offset, not enabling DST support. Invalid or dynamic feed declarations block same-name fallback bindings.

    Filter::matches now raises on evaluation failure. ReportOutcome adds EvaluationFailed; servers must map it separately from filter preconditions. Direct Filter record construction also needs request_timezone.

    #Run

    moon run demo --target native moon run demo --target native -- https://example.com/calendar.ics moon run cmd/serve --target native -- ./caldata 8437

    The demo prints typed events; it does not expand occurrences. Discovery starts at /.well-known/caldav, and the calendar home is http://127.0.0.1:8437/cal/. The server has no authentication or TLS. Use a reverse proxy providing both before exposing it beyond a trusted host.

    Keep server logs outside the calendar data directory: the store treats files there as resources.

    #Query behavior

    calendar-query applies component, property, parameter, and time-range filters. Temporal tests parse only the dates they need. Unsupported recurrence or time zones do not prevent a SUMMARY-only search, GET, or multiget.

    A successful empty series stays empty. The server does not restore its master or return a successful empty result when it cannot prove the queried window has been covered. Evaluation failure returns 500, with a resource href and a fixed error category, not the raw calendar line or exception. It does not return a partial multistatus.

    Request preconditions return 403 with the applicable valid-filter, supported-filter, or supported-collation element. Invalid checked request timezone fields return valid-calendar-data. Resource calculation failures are not mislabeled as unsupported filters.

    #Verification

    moon check --target all --deny-warn moon test --target all --deny-warn moon fmt --check moon info python -I tools/s5_acceptance.py python -I tools/s6_acceptance.py

    On 2026-10-31, the working tree passed 251 wasm, 234 wasm-gc, 251 JavaScript, and 261 native tests, including the checked example above. S5 passed 24 checks and S6 passed 47. Both scripts start and stop isolated servers. A separate tools/s6_evaluation_acceptance.mbtx driver checks RDATE, query completeness, fixed/dynamic zones, and private-data sentinels in HTTP responses and logs. Run it against an empty isolated server as described in OpenWiki server notes.

    New input-driven behavior needs differential tests, empty-result checks, and specific failure assertions. The capability-to-evidence matrix is in the development handbook.

    #Client interoperability

    Client or driverDiscoveryRead/listCreate/update/deleteEvidence
    curl over TCPYesYesYesS5 24/24 and S6 47/47; a separate evaluation driver also passes
    Thunderbird 155.0.1 (Windows)YesYesYesEarlier localhost session verified seed read, create, in-place update, and delete in vdir
    DAVx5Not runNot runNot runAndroid device required
    Apple CalendarNot runNot runNot runmacOS/iOS device required

    The Thunderbird session has not been repeated for the 0.5.0 changes. It did not exercise MKCALENDAR or temporal filtering. Client CRUD does not prove complete protocol or calendar semantics.

    #Boundaries

    • No IANA tzdb or dynamic VTIMEZONE conversion. Typed dates referencing an unbound regional TZID or unsupported declaration fail rather than use a guessed seasonal offset. Raw component trees remain available.
    • No sub-daily FREQ or BYWEEKNO/BYYEARDAY/BYHOUR/BYMINUTE/BYSECOND. These rules are rejected; temporal REPORT evaluation fails explicitly.
    • No RDATE VALUE=PERIOD expansion. DATE/DATE-TIME is supported.
    • Request timezone conversion is not implemented. A request containing it fails when any temporal test is evaluated; text-only queries can succeed. Its validation checks structure and required fields, not all observance RRULE semantics.
    • Repeated components other than VEVENT are not expanded for time-range. Nonrecurring VTODO uses its RFC 4791 task-state table. VALARM time-range is refused with supported-filter; relative triggers are not resolved.
    • Time-range queries use up to 4096 raw RRULE instances per UID series; finite RDATE values are added separately. A proven match can succeed; an unproven negative result fails. Overrides require conservative completeness checks rather than an unshifted frontier.
    • Floating times retain the library's existing comparison convention; it does not choose a user's local time zone.
    • No CalDAV scheduling, ACL system, built-in TLS, provider adapters, cloud account synchronization, or CalDAV client.
    • PROPFIND and REPORT honor the requested DAV:prop set: answers are trimmed to it, unanswerable names get their own 404 propstat, and calendar-data (not a WebDAV property) is report-only — in PROPFIND it answers 404. Matching is by local name, and the 404 echo carries the DAV: prefix regardless of the request's.
    • MKCALENDAR creates a collection but does not persist request properties.
    • Request bodies need Content-Length; chunked uploads get 411. After an oversized or chunked body, draining stops at 10 MB; a longer running upload can lose the refusal response to the close-time reset.
    • The XML shape parser matches local element names without full namespace URI validation, skips DOCTYPE to its first >, and reads only the first top-level element. Numeric references decode within the BMP; astral-plane references stay verbatim.
    • Concurrent connections are not capped. The default bind is 127.0.0.1.
    • /cal/ is both home and default collection. MKCALENDAR collections sit beside existing events. A bare top-level VEVENT yields no typed events.
    • EXDATE at an override's original slot removes it; the override does not resurrect that instance.

    See OpenWiki for the package map and calculation contracts. This is an independent implementation under Apache-2.0; THIRD-PARTY-NOTICES.md records the test corpus source.

    Byday

    One BYDAY entry: a weekday, optionally qualified by an ordinal.

    TU is any Tuesday (ordinal = 0), 1FR the first Friday of the interval, -2MO the second-to-last Monday. RFC 5545 bounds the ordinal to ±53; expansion of qualified weekdays arrives with S8.

    Component

    One iCalendar component: its kind, its own properties in wire order, and any nested components. Nesting is real (VALARM lives inside VEVENT, VEVENT inside VCALENDAR), so the model keeps a tree instead of a flat list, and properties stay in the order the feed sent them.

    Event

    One calendar event, mapped from a VEVENT component (RFC 5545 §3.6.1).

    This is a typed view over the component tree, not a replacement for it: unknown properties stay in the Component and nothing is dropped. Every field is optional because RFC 5545 makes every VEVENT property optional; a property that is present but malformed raises [@text.ParseError] instead of being silently skipped, so a broken feed is loud rather than subtly wrong. A property that is simply absent is None — absence is not breakage. An event that states no DTEND ends where its DURATION says it does (RFC 5545 §3.8.5.3 offers DURATION as the alternative end); carrying both is the spec violation it names and raises.

    Recurrence dates and overrides are retained for the rrule package's series union, exclusions, and override merge.

    ExpandError

    Why an expansion can fail even though the rule parsed.

    Freq

    How often a recurrence repeats: the FREQ clause of RFC 5545 §3.3.10.

    Only the four calendar grades are representable, on purpose. The finer HOURLY, MINUTELY, and SECONDLY grades fall outside this project's boundary (docs/development.html §08), so [@rrule.parse_rule] rejects them with an explicit error instead of silently narrowing or dropping them.

    IcalDateTime

    A parsed iCalendar date-time value (DTSTART, DTEND, DUE, UNTIL, EXDATE, ...).

    iCalendar writes wall-clock readings rather than instants, so the wall time is kept next to the offset that says where it should be read:

    • DTSTART:20260908T013000Z → utc_offset = Some(0)
    • DTSTART;TZID=Asia/Shanghai:20260908T093000 → utc_offset = Some(28800)
    • DTSTART:20260908T093000 → utc_offset = None (floating: the feed declared no zone, so it means 09:30 wherever it is read)
    • DTSTART;VALUE=DATE:20260908 → all_day = true, wall time at midnight

    moonbitlang/x/time supplies the calendar arithmetic; the offset stays a plain Int instead of a Zone because named zones are resolved through a fixed-offset table (see [ZoneTable] and seam S2 in docs/upstream-seams.md).

    Occurrence

    One effective occurrence after RRULE expansion, EXDATE removal, and RECURRENCE-ID override merging.

    ParseError

    A line-level iCalendar parse failure.

    BadLine is raised by the content-line and component layers: line_no is 1-based over logical (unfolded) lines and line keeps the offending text, so a caller can point a user at the exact place a feed broke instead of just reporting "invalid iCalendar". BadRule is raised by value-level parsers such as @rrule.parse_rule, where a whole RRULE value is the unit of failure and no line context applies.

    Rule

    A parsed RRULE value (RFC 5545 §3.3.10): the syntax of a recurrence rule, not its expansion.

    Every clause within the project's support boundary is kept in a typed field, whichever milestone will expand it — the first-tier clauses (INTERVAL / COUNT / UNTIL / plain BYDAY / positive BYMONTHDAY / BYMONTH) with S3, the second-tier ones (ordinal BYDAY, negative BYMONTHDAY, BYSETPOS, WKST) with S8. Clauses outside the boundary never reach a Rule: [@rrule.parse_rule] rejects them loudly.

    Defaults follow the RFC: interval = 1 and wkst = Monday when their clauses are absent, and every BY* list is empty when absent.

    expand

    Expand a parsed [Rule] against its DTSTART into the occurrence date-times of the series, in chronological order (RFC 5545 §3.3.10).

    Supports the calendar-grade RFC 5545 rules in this project: DAILY / WEEKLY / MONTHLY / YEARLY, ordinal BYDAY, positive and negative BYMONTHDAY, BYSETPOS, BYMONTH, and WKST. The semantic checks that need the DTSTART (COUNT + UNTIL exclusivity, UNTIL value-type agreement) happen here.

    Occurrences are wall-clock arithmetic: every occurrence carries the DTSTART's clock time, UTC offset, zone spelling, and all-day flag unchanged (see [@model.IcalDateTime::on_date]). The binding is explicitly fixed; dynamic TZIDs are rejected during parsing. A DTSTART that does not match the rule is not forced into the series: the first occurrence is the first matching date, exactly as the reference corpus behaves.

    COUNT counts occurrences from the first match (RFC 5545 counts the DTSTART only when it matches); UNTIL bounds the series inclusively, compared by instant. limit caps how many occurrences are returned — the safety valve for unbounded rules — and never truncates a COUNT/UNTIL rule that ends within it. A series whose next candidate would fall past the representable calendar (year 9999 in moonbitlang/x) ends there rather than raising, whatever INTERVAL says — the huge-interval products are computed in 64-bit for the same reason: a wrapped 32-bit product can name a valid but wrong date.

    Example

    fn test_example() raise {
    let rule = @rrule.parse_rule("FREQ=DAILY;COUNT=3")
    let dtstart = @model.parse_single_date_time(
    "20260901T090000Z",
    @model.ZoneTable::empty(),
    )
    let occurrences = @rrule.expand(rule, dtstart)
    assert_eq(occurrences.length(), 3)
    assert_eq(occurrences[2].to_string(), "2026-09-03T09:00:00Z")
    }

    expand_series

    Expand and merge one UID's VEVENT series. A cancelled override removes its instance; a moved override replaces that instance; RANGE=THISANDFUTURE shifts the selected instance and every later generated instance by the same wall-clock delta, and a duration modified on the override (an explicit DTEND) becomes the duration of every later instance — RFC 5545 §3.8.4.4.

    parse_calendar

    fn parse_calendar(input : String) -> Array[
    Component
    ] raise

    Parse a complete iCalendar document into its lossless component trees. Unknown components and properties remain available for inspection and serialization.

    parse_events

    fn parse_events(input : String) -> Array[
    Event
    ] raise

    Parse a whole iCalendar feed into typed events: unfold the text, build the component tree, register fixed zones and unsupported declarations, then map every VEVENT. Referenced unsupported zones raise.

    Example

    fn test_example() raise {
    let events = @model.parse_events(
    "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nSUMMARY:Sync\r\nEND:VEVENT\r\nEND:VCALENDAR",
    )
    assert_eq(events.length(), 1)
    assert_eq(events[0].summary, Some("Sync"))
    }

    parse_rule

    fn parse_rule(rule : String) ->
    Rule
    raise

    Parse an RRULE property value (RFC 5545 §3.3.10) into a [Rule].

    This is the syntax layer only. Every clause inside the project's support boundary (docs/development.html §08) is parsed into a typed field; the clauses outside it — the HOURLY / MINUTELY / SECONDLY frequencies and the BYWEEKNO / BYYEARDAY / BYHOUR / BYMINUTE / BYSECOND clauses — are rejected with an explicit [@text.ParseError::BadRule] rather than silently dropped.

    The RRULE: property-name prefix may be present or absent, so both a bare property value and a whole content line parse. Clause names and values match case-insensitively (real feeds mix cases). Each clause may appear at most once, and FREQ must appear exactly once.

    Two deliberate deviations from the RFC grammar, in the direction of tolerating real feeds: FREQ is not required to be the first clause, and no DTSTART-dependent semantic checks (COUNT + UNTIL exclusivity, UNTIL value-type agreement) happen here — those belong to expansion (S3), which is the only place that knows the DTSTART.

    Example

    fn test_example() raise {
    let rule = @rrule.parse_rule("FREQ=WEEKLY;BYDAY=TU,TH;COUNT=10")
    assert_true(rule.freq is @rrule.Freq::Weekly)
    assert_eq(rule.count, Some(10))
    assert_eq(rule.byday.length(), 2)
    }

    serialize_component

    fn serialize_component(root :
    Component
    ) -> String

    Serialize a single root component; see [serialize_components].

    serialize_components

    fn serialize_components(roots : Array[
    Component
    ]) -> String

    Serialize a whole component forest back into iCalendar text: BEGIN:KIND, every property line, every child component, END:KIND, CRLF throughout (RFC 5545 §3.1), and every physical line within [FOLD_LIMIT] octets.

    Property values are written in their escaped wire form, exactly as they were parsed — this layer folds, it does not re-escape — so a feed that was parsed into a tree and written back out loses nothing. Property and parameter names were normalised to upper case at parse time and stay that way; parameter values whose content would read back as structure (, ; : ") are re-quoted.

    Example

    fn test_example() raise {
    let roots = @model.parse_components([
    "BEGIN:VCALENDAR", "SUMMARY:Sync", "END:VCALENDAR",
    ])
    assert_eq(
    @serialize.serialize_components(roots),
    "BEGIN:VCALENDAR\r\nSUMMARY:Sync\r\nEND:VCALENDAR\r\n",
    )
    }

    Source Files