//! Pure iCal RRULE expansion — the port of `packages/core/src/engine/rrule.ts`.//!//! Deterministic, no external calendar library, and every step of the calendar//! arithmetic performed in an EXPLICIT IANA ZONE that the caller must name.//!//! The zone is not a nicety. The engine used to read the RUNTIME's zone, and//! that was a live duplication bug the moment a second producer appeared: the//! phone runs in Asia/Kolkata, the server on a host whose local zone is//! Europe/Berlin. Both materialise occurrences from the same rule, and a//! materialised occurrence's row id is DERIVED from//! `(recurrence, occurrence_at)` — so two zones meant two instants, two ids, no//! unique-constraint conflict, and the person seeing every recurring todo//! twice, an hour apart. Passing the zone is what makes the two producers//! agree; a THIRD producer in another language is exactly why the answers here//! are pinned to Node rather than merely reasoned about.//!//! The zone is the WORKSPACE's, never the device's: a person who lands in//! another country must not start minting a second copy of every occurrence.//!//! Arithmetic is DST-aware — a daily 09:00 event stays 09:00 wall-clock across//! a spring-forward boundary, so the UTC instant shifts by the offset delta.//! Supports `FREQ` = DAILY/WEEKLY/MONTHLY/YEARLY, `INTERVAL`, `COUNT`, `UNTIL`//! and `BYDAY` (weekly). Month and day edges (the 31st, Feb-29) are SKIPPED in//! months that lack the day — never rolled forward (iCal semantics).//!//! **Instants are `i64` epoch milliseconds**, where the TypeScript passes//! `Date`; a pure library may not construct a clock.use std::ops::ControlFlow;usecrate::zoned_clock::{ civil_from_days, date_utc, day_number, days_in_month, instant_from_zoned, weekday_of_day_number, zoned_parts, ZoneError, ZonedParts,};/// The frequencies Cotton supports.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumRruleFreq {Daily,Weekly,Monthly,Yearly,}implRruleFreq {/// The iCal spelling.pubconstfn as_str(self) -> &'static str {matchself {RruleFreq::Daily => "DAILY",RruleFreq::Weekly => "WEEKLY",RruleFreq::Monthly => "MONTHLY",RruleFreq::Yearly => "YEARLY", } }/// In the order the error message lists them.pubconst ALL: [RruleFreq; 4] = [RruleFreq::Daily,RruleFreq::Weekly,RruleFreq::Monthly,RruleFreq::Yearly, ];}impl std::fmt::DisplayforRruleFreq {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}/// A parsed rule.#[derive(Debug, Clone, PartialEq, Eq)]pubstructParsedRrule {pub freq: RruleFreq,pub interval: i64,pub count: Option<i64>,/// Epoch milliseconds.pub until: Option<i64>,/// Weekly `BYDAY` as JS weekday indices (Sun = 0 … Sat = 6), in the given/// order.pub byday: Vec<i64>,}/// An inclusive window of epoch milliseconds.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructDateRange {pub from: i64,pub to: i64,}/// Why a rule or a date could not be read. The sentences are the TypeScript's,/// verbatim — they reach an assistant through a tool error and a person through/// the event form.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pubenumRruleError { #[error("Unsupported RRULE FREQ: {0}. Allowed: DAILY, WEEKLY, MONTHLY, YEARLY")]UnsupportedFreq(String), #[error("Invalid RRULE INTERVAL: {0}")]InvalidInterval(String), #[error("Invalid RRULE COUNT: {0}")]InvalidCount(String), #[error("Invalid RRULE BYDAY token: {0}")]InvalidByday(String), #[error("Invalid iCal date: {0}")]InvalidIcalDate(String), #[error(transparent)]Zone(#[from] ZoneError),}fn weekday_index(code: &str) -> Option<i64> {Some(match code {"SU" => 0,"MO" => 1,"TU" => 2,"WE" => 3,"TH" => 4,"FR" => 5,"SA" => 6, _ => returnNone, })}/// Hard cap on generator iterations — a malformed rule, or an unbounded one/// over a huge window, cannot hang the caller.pubconst MAX_ITERATIONS: usize = 100_000;/// Parse an iCal RRULE string (the value after `RRULE:`, or the bare rule).////// Refuses a missing or unknown `FREQ`: schema drift must surface, never/// silently degrade to a single occurrence.pubfn parse_rrule(rrule: &str) -> Result<ParsedRrule, RruleError> {let body = strip_rrule_prefix(rrule);letmut map: Vec<(String, String)> = Vec::new();for part in body.split(';') {let part = part.trim();if part.is_empty() {continue; }letSome(eq) = part.find('=') else { continue };let key = part[..eq].to_uppercase();let value = part[eq + 1..].to_string();// A `Map` overwrites; a repeated key keeps the LAST one.ifletSome(existing) = map.iter_mut().find(|(k, _)| *k == key) { existing.1 = value; } else { map.push((key, value)); } }let get = |key: &str| -> Option<&str> { map.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()) };let freq_raw = get("FREQ").unwrap_or("").to_uppercase();let freq = RruleFreq::ALL .into_iter() .find(|f| f.as_str() == freq_raw) .ok_or_else(|| RruleError::UnsupportedFreq(json_quote(&freq_raw)))?;let interval = match get("INTERVAL") {// `Number.parseInt(raw, 10) || 1` is NOT what the TypeScript does — an// EMPTY string is falsy in JavaScript, so `INTERVAL=` takes the default// rather than failing. Mirrored exactly.Some(raw) if !raw.is_empty() => {let parsed = js_parse_int_10(raw);match parsed {Some(value) if value >= 1 => value, _ => returnErr(RruleError::InvalidInterval(json_quote(raw))), } } _ => 1, };let count = match get("COUNT") {Some(raw) if !raw.is_empty() => {let parsed = js_parse_int_10(raw);match parsed {Some(value) if value >= 0 => Some(value), _ => returnErr(RruleError::InvalidCount(json_quote(raw))), } } _ => None, };let until = match get("UNTIL") {Some(raw) => Some(parse_ical_date(raw)?),None => None, };letmut byday: Vec<i64> = Vec::new();for token in get("BYDAY").unwrap_or("").split(',') {let token = token.trim().to_uppercase();if token.is_empty() {continue; }// Strip any ordinal prefix (e.g. "2MO"); Cotton v1 supports plain// weekdays. `slice(-2)` is the LAST TWO UTF-16 units, so a one-unit// token is itself and fails the lookup.let units: Vec<u16> = token.encode_utf16().collect();let tail: String = if units.len() >= 2 {String::from_utf16_lossy(&units[units.len() - 2..]) } else { token.clone() };let index = weekday_index(&tail).ok_or_else(|| RruleError::InvalidByday(json_quote(&token)))?; byday.push(index); }Ok(ParsedRrule { freq, interval, count, until, byday, })}/// A repeating todo's rule, read strictly (7 Nov 2026, decision 7): the keys a/// todo keeps are FREQ, INTERVAL, COUNT, UNTIL, a weekly BYDAY of plain/// weekdays, and WKST (read and ignored); anything else is refused in words,/// never silently re-read. A date-only UNTIL is the end of that day, UTC./// The phone's todo paths and the Worker both read todo rules with this; the/// calendar reads imported events with the lenient [`parse_rrule`].////// Vectors: `vectors/todo_rule.json`.pubfn parse_todo_rule(text: &str) -> Result<ParsedRrule, String> {let quote = |raw: &str| json_quote(raw);let say = |key: &str, fills: &[(&str, &str)]| crate::lines::resolve("refusal", key, fills);let body = strip_rrule_prefix(text.trim());letmut parts: Vec<(String, String)> = Vec::new();for part in body.split(';') {if part.trim().is_empty() {continue; }let eq = part.find('=').filter(|eq| *eq >= 1).ok_or_else(|| say("recurrence.not_key_value", &[("part", "e(part))]))?;let key = part[..eq].trim().to_uppercase();let value = part[eq + 1..].trim().to_string();match parts.iter_mut().find(|(k, _)| *k == key) {Some(existing) => existing.1 = value,None => parts.push((key, value)), } }ifletSome((unknown, _)) = parts.iter().find(|(k, _)| !["FREQ", "INTERVAL", "COUNT", "UNTIL", "BYDAY", "WKST"].contains(&k.as_str())) {returnErr(say("recurrence.key_not_kept", &[("key", unknown)])); }let get = |key: &str| parts.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());let freq_raw = get("FREQ").unwrap_or("");let freq = RruleFreq::ALL .into_iter() .find(|f| f.as_str() == freq_raw.to_uppercase()) .ok_or_else(|| say("recurrence.freq", &[("freq", "e(freq_raw))]))?;let whole = |part: &str, min: i64| -> Result<Option<i64>, String> {letSome(raw) = get(part).filter(|raw| !raw.is_empty()) else { returnOk(None) };match raw.parse::<i64>() {Ok(n) if raw.bytes().all(|b| b.is_ascii_digit()) && n >= min => Ok(Some(n)), _ => Err(say("recurrence.whole", &[("part", part), ("value", "e(raw))])), } };let interval = whole("INTERVAL", 1)?.unwrap_or(1);let count = whole("COUNT", 1)?;let until = match get("UNTIL") {None => None,Some(raw) => Some(todo_until(raw).ok_or_else(|| say("recurrence.until", &[("value", "e(raw))]))?), };letmut byday: Vec<i64> = Vec::new();for day in get("BYDAY").unwrap_or("").split(',') {let day = day.trim().to_uppercase();if day.is_empty() {continue; }let index = weekday_index(&day).ok_or_else(|| say("recurrence.byday", &[("day", "e(&day))]))?;if !byday.contains(&index) { byday.push(index); } }if !byday.is_empty() && freq != RruleFreq::Weekly {returnErr(say("recurrence.byday_weekly_only", &[])); } byday.sort_unstable();Ok(ParsedRrule { freq, interval, count, until, byday })}implParsedRrule {/// As the Worker reads it: weekday codes Sunday first, UNTIL an ISO instant.pubfn to_json(&self) -> serde_json::Value {const CODES: [&str; 7] = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"]; serde_json::json!({"freq": self.freq.as_str(),"interval": self.interval,"count": self.count,"until": self.until.and_then(crate::js::to_iso_string),"byday": self.byday.iter().filter_map(|d| usize::try_from(*d).ok().and_then(|d| CODES.get(d))).collect::<Vec<_>>(), }) }}/// A todo rule's UNTIL: `YYYYMMDD` (the end of that day, UTC),/// `YYYYMMDDTHHMMSS[Z]` (UTC), or an ISO instant.fn todo_until(raw: &str) -> Option<i64> {let bytes = raw.as_bytes();if bytes.len() == 8 && bytes.iter().all(u8::is_ascii_digit) {let (year, month, day): (i64, i64, i64) = (raw[0..4].parse().ok()?, raw[4..6].parse().ok()?, raw[6..8].parse().ok()?);returnSome(date_utc(year, month - 1, day, 23, 59, 59, 0)); } parse_ical_basic(raw).or_else(|| crate::js::parse_date_ms(raw))}/// `rrule.replace(/^RRULE:/i, "")`.fn strip_rrule_prefix(rrule: &str) -> &str {if rrule.len() >= 6 && rrule[..6].eq_ignore_ascii_case("RRULE:") { &rrule[6..] } else { rrule }}/// Parse an iCal `UNTIL` value (`YYYYMMDD` or `YYYYMMDDTHHMMSS[Z]`) to epoch/// milliseconds.////// A zone-less iCal value is read as UTC, never as the RUNTIME's local zone./// `UNTIL` is compared as an instant, so a locally-parsed one would land hours/// apart on the phone and the server and could flip whether the final/// occurrence exists — the same class of bug as the expansion itself. Floating/// iCal times are rare (`UNTIL` almost always carries `Z`) and a fixed reading/// is worth more here than a nominally more correct one that differs per/// machine.pubfn parse_ical_date(value: &str) -> Result<i64, RruleError> {let v = value.trim();ifletSome(parsed) = parse_ical_basic(v) {returnOk(parsed); }// Fall back to native parsing for the ISO strings callers may pass.crate::js::parse_date_ms(v) .ok_or_else(|| RruleError::InvalidIcalDate(json_quote(value)))}/// `/^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/`.fn parse_ical_basic(v: &str) -> Option<i64> {let bytes = v.as_bytes();if bytes.len() != 8 && bytes.len() != 15 && bytes.len() != 16 {returnNone; }if !bytes[..8].iter().all(u8::is_ascii_digit) {returnNone; }let year: i64 = v[0..4].parse().ok()?;let month: i64 = v[4..6].parse().ok()?;let day: i64 = v[6..8].parse().ok()?;let (hour, minute, second) = if bytes.len() == 8 { (0, 0, 0) } else {if bytes[8] != b'T' || !bytes[9..15].iter().all(u8::is_ascii_digit) {returnNone; }if bytes.len() == 16 && bytes[15] != b'Z' {returnNone; } ( v[9..11].parse().ok()?, v[11..13].parse().ok()?, v[13..15].parse().ok()?, ) };// The `Z` is matched and then IGNORED, exactly as the TypeScript ignores// it: the value is read as UTC either way.Some(date_utc(year, month - 1, day, hour, minute, second, 0))}// ─────────────────────────────────────────────────────────────────────────────// Wall-clock arithmetic.// ─────────────────────────────────────────────────────────────────────────────/// A wall-clock reading in the target zone, plus the milliseconds the zone/// conversion does not carry.////// All calendar arithmetic happens on these — plain integers — and only the/// conversion at either end knows about zones. The READER itself lives in/// [`crate::zoned_clock`] and is shared with the news scheduler: two/// implementations of "what hour is it in zone X" is the same class of mistake/// as two implementations of "who wins" in the fold.#[derive(Debug, Clone, Copy, PartialEq, Eq)]structWall { parts: ZonedParts, ms: i64,}/// What a clock in `zone` reads at this instant.fn wall_of(instant: i64, zone: &str) -> Result<Wall, ZoneError> {Ok(Wall { parts: zoned_parts(instant, zone)?,// A zone reader has no sub-second field; milliseconds are// zone-invariant anyway. ms: instant.rem_euclid(1000), })}/// The instant at which a clock in `zone` reads these components.fn instant_of(w: Wall, zone: &str) -> Result<i64, ZoneError> { instant_from_zoned(w.parts, w.ms, zone)}/// Days since the epoch for a wall DATE — time-of-day and zone dropped.fn day_number_of(w: Wall) -> i64 { day_number(w.parts.year, w.parts.month, w.parts.day)}/// The same time-of-day, on the calendar day `days` later.fn add_days(w: Wall, days: i64) -> Wall {let (year, month, day) = civil_from_days(day_number_of(w) + days);Wall { parts: ZonedParts { year, month, day, ..w.parts }, ms: w.ms, }}/// Weekday of a wall date, Sun = 0 … Sat = 6.fn weekday_of(w: Wall) -> i64 { weekday_of_day_number(day_number_of(w))}/// The Monday (the `WKST` default) of the week containing `w`, at `w`'s wall/// time.fn monday_of(w: Wall) -> Wall { add_days(w, -((weekday_of(w) + 6) % 7))}/// Advance by whole months, preserving wall time; `None` when the target month/// lacks the day-of-month (the 31st rule).fn add_months_exact(w: Wall, months: i64) -> Option<Wall> {let total = w.parts.year * 12 + (w.parts.month - 1) + months;let year = total.div_euclid(12);let month = total - year * 12 + 1;if w.parts.day > days_in_month(year, month) {returnNone; }Some(Wall { parts: ZonedParts { year, month, ..w.parts }, ms: w.ms, })}/// Advance by whole years, preserving wall time; `None` for Feb-29 in a/// non-leap year.fn add_years_exact(w: Wall, years: i64) -> Option<Wall> {let year = w.parts.year + years;if w.parts.day > days_in_month(year, w.parts.month) {returnNone; }Some(Wall { parts: ZonedParts { year, ..w.parts }, ms: w.ms, })}/// Yield occurrence start instants in chronological order, starting at/// `dtstart` (which is always the first occurrence, except a weekly `BYDAY`/// rule whose dtstart weekday is excluded).////// Never applies `COUNT`/`UNTIL`/range — the consumer does, so `COUNT` can/// count occurrences that fall before the window.////// Where the TypeScript is a `function*` the consumer breaks out of, this/// takes the consumer as a callback returning [`ControlFlow`]. Same shape, no/// self-referential iterator: the two consumers below are both early-exiting/// folds.fn generate<F>( dtstart: i64, r: &ParsedRrule, zone: &str,mut on_occurrence: F,) -> Result<(), RruleError>where F: FnMut(i64) -> ControlFlow<()>,{let anchor = wall_of(dtstart, zone)?;if r.freq == RruleFreq::Weekly && !r.byday.is_empty() {let anchor_monday = day_number_of(monday_of(anchor));for offset in0..MAX_ITERATIONS as i64 {let occ = add_days(anchor, offset);let week_index = js_math_round((day_number_of(monday_of(occ)) - anchor_monday) as f64 / 7.0);if week_index % r.interval == 0 && r.byday.contains(&weekday_of(occ)) {let instant = instant_of(occ, zone)?;if instant >= dtstart && on_occurrence(instant).is_break() {returnOk(()); } } }returnOk(()); }for n in0..MAX_ITERATIONS as i64 {let occ = match r.freq {RruleFreq::Daily => Some(add_days(anchor, n * r.interval)),RruleFreq::Weekly => Some(add_days(anchor, n * r.interval * 7)),RruleFreq::Monthly => add_months_exact(anchor, n * r.interval),RruleFreq::Yearly => add_years_exact(anchor, n * r.interval), };ifletSome(occ) = occ {let instant = instant_of(occ, zone)?;if on_occurrence(instant).is_break() {returnOk(()); } } }Ok(())}/// `Math.round` as an integer. The argument here is a difference of two Mondays/// over seven and is therefore always whole, so the half-rounding rule does not/// bite — but it is taken from the one implementation anyway, because "it/// happens to be an integer" is an invariant a future BYDAY change could/// quietly break.fn js_math_round(value: f64) -> i64 {crate::js_number::math_round(value) as i64}/// Expand an RRULE into the concrete occurrence start instants that fall within/// `[range.from, range.to]` (inclusive).////// `COUNT`/`UNTIL` are honoured against the full occurrence stream — an/// occurrence before the window still consumes `COUNT`.pubfn expand_rrule( rrule: &str, dtstart: i64, range: DateRange, zone: &str,) -> Result<Vec<i64>, RruleError> { expand_parsed(&parse_rrule(rrule)?, dtstart, range, zone)}/// [`expand_rrule`] over a rule already read (a todo's, by [`parse_todo_rule`]).pubfn expand_parsed( r: &ParsedRrule, dtstart: i64, range: DateRange, zone: &str,) -> Result<Vec<i64>, RruleError> {letmut out: Vec<i64> = Vec::new();letmut emitted: i64 = 0; generate(dtstart, r, zone, |occ| {if r.count.is_some_and(|count| emitted >= count) {returnControlFlow::Break(()); }if r.until.is_some_and(|until| occ > until) {returnControlFlow::Break(()); } emitted += 1;if occ > range.to {returnControlFlow::Break(()); }if occ >= range.from { out.push(occ); }ControlFlow::Continue(()) })?;Ok(out)}/// The first occurrence STRICTLY after `after`, or `None` when the rule is/// exhausted (`COUNT` spent, `UNTIL` passed) before reaching one.////// `COUNT` is consumed by every occurrence from dtstart, same as/// [`expand_rrule`].pubfn next_occurrence_after( rrule: &str, dtstart: i64, after: i64, zone: &str,) -> Result<Option<i64>, RruleError> { next_after_parsed(&parse_rrule(rrule)?, dtstart, after, zone)}/// [`next_occurrence_after`] over a rule already read.pubfn next_after_parsed( r: &ParsedRrule, dtstart: i64, after: i64, zone: &str,) -> Result<Option<i64>, RruleError> {letmut emitted: i64 = 0;letmut answer: Option<i64> = None; generate(dtstart, r, zone, |occ| {if r.count.is_some_and(|count| emitted >= count) {returnControlFlow::Break(()); }if r.until.is_some_and(|until| occ > until) {returnControlFlow::Break(()); } emitted += 1;if occ > after { answer = Some(occ);returnControlFlow::Break(()); }ControlFlow::Continue(()) })?;Ok(answer)}/// One occurrence of a (possibly recurring) event.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructExpandedOccurrence {pub starts_at: i64,pub ends_at: Option<i64>,}/// An event, as much of it as the expansion reads.#[derive(Debug, Clone, PartialEq, Eq)]pubstructEventForExpansion {pub starts_at: i64,pub ends_at: Option<i64>,pub rrule: Option<String>,}/// Expand a (possibly recurring) event into concrete occurrences overlapping/// the window, preserving each occurrence's duration.////// A non-recurring event yields at most one occurrence (when it overlaps the/// window). Recurring occurrences that START before `from` but END inside the/// window are included — which is why the search widens backwards by one/// duration before filtering by true overlap.pubfn expand_event( event: &EventForExpansion, range: DateRange, zone: &str,) -> Result<Vec<ExpandedOccurrence>, RruleError> {let start = event.starts_at;let end = event.ends_at;let duration_ms = end.map_or(0, |end| end - start);letSome(rrule) = event.rrule.as_deref().filter(|rule| !rule.is_empty()) else {// `!event.rrule` in JavaScript is true for `null`, `undefined` AND the// empty string, so an empty rule is "not recurring", not a parse error.let effective_end = end.unwrap_or(start);let overlaps = start <= range.to && effective_end >= range.from;returnOk(if overlaps { vec![ExpandedOccurrence { starts_at: start, ends_at: end, }] } else {Vec::new() }); };let search_from = range.from - duration_ms;let starts = expand_rrule( rrule, start,DateRange { from: search_from, to: range.to, }, zone, )?;letmut result: Vec<ExpandedOccurrence> = Vec::new();for occ_start in starts {let occ_end = end.map(|_| occ_start + duration_ms);let occ_effective_end = occ_end.unwrap_or(occ_start);if occ_start <= range.to && occ_effective_end >= range.from { result.push(ExpandedOccurrence { starts_at: occ_start, ends_at: occ_end, }); } }Ok(result)}// ─────────────────────────────────────────────────────────────────────────────// JavaScript semantics the error messages and the parser depend on.// ─────────────────────────────────────────────────────────────────────────────/// `JSON.stringify(someString)` — the error messages quote the offending token/// through it, so a caller sees `"MONTLY"` with the quotes.fn json_quote(value: &str) -> String {crate::js::json_stringify(&serde_json::Value::String(value.to_string()))}/// `Number.parseInt(value, 10)`, answering `None` where it answers `NaN`.////// Leading whitespace is skipped, an optional sign is taken, digits are read/// until the first non-digit and the rest is DISCARDED — so `"3x"` is 3 and/// `"x"` is `NaN`. Getting that wrong would make `INTERVAL=2WEEKS` a refusal/// where the TypeScript quietly reads 2.fn js_parse_int_10(value: &str) -> Option<i64> {let trimmed = value.trim_start_matches(crate::js::is_js_whitespace);let bytes = trimmed.as_bytes();let (negative, rest) = match bytes.first() {Some(b'-') => (true, &bytes[1..]),Some(b'+') => (false, &bytes[1..]), _ => (false, bytes), };let digits: Vec<u8> = rest .iter() .copied() .take_while(u8::is_ascii_digit) .collect();if digits.is_empty() {returnNone; }let magnitude: i64 = std::str::from_utf8(&digits).ok()?.parse().ok()?;Some(if negative { -magnitude } else { magnitude })}#[cfg(test)]#[path = "rrule_tests.rs"]mod tests;