rrule-temporal 0.1.7 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,13 @@
1
1
  # rrule-temporal
2
2
 
3
- Recurrence rule (RFC 5545) processing using Temporal PlainDate/PlainDateTime.
3
+ Recurrence rule (RFC 5545) processing built on the Temporal API.
4
+ The library accepts the familiar `RRULE` format and returns
5
+ `Temporal.ZonedDateTime` instances for easy time‑zone aware scheduling.
4
6
 
5
- This was created to advance the rrule library to use Temporal, and to provide a more modern API, as the original rrule library is [not maintained anymore](https://github.com/jkbrzt/rrule/issues/615). Maintainers suggested to use Temporal instead of Date:
7
+ See the [demo site](https://ggaabe.github.io/rrule-temporal/) for an interactive playground.
6
8
 
7
- https://github.com/jkbrzt/rrule/issues/450#issuecomment-1055853095
9
+ > This was created to advance the rrule library to use Temporal, and to provide a more modern API, as the original rrule library is [not maintained anymore](https://github.com/jkbrzt/rrule/issues/615). Maintainers suggested to use Temporal instead of Date:
10
+ >https://github.com/jkbrzt/rrule/issues/450#issuecomment-1055853095
8
11
 
9
12
  ## Installation
10
13
 
@@ -12,192 +15,106 @@ https://github.com/jkbrzt/rrule/issues/450#issuecomment-1055853095
12
15
  npm install rrule-temporal
13
16
  ```
14
17
 
15
- ## Usage
18
+ ## Quick start
16
19
 
17
- ## 1. Parsing an ICS snippet
18
-
19
- Parse a full DTSTART/RRULE snippet and reproduce it or enumerate all occurrences:
20
-
21
- ```typescript
22
- // Daily at 17:00 America/Chicago, 5 total occurrences
23
- const ics = `
24
- DTSTART;TZID=America/Chicago:20250320T170000
25
- RRULE:FREQ=DAILY;BYHOUR=17;BYMINUTE=0;COUNT=5
26
- `.trim();
27
-
28
- const rule = new RRuleTemporal({ rruleString: ics });
29
-
30
- // toString() outputs the original DTSTART and RRULE line:
31
- console.log(rule.toString());
32
- /*
33
- DTSTART;TZID=America/Chicago:20250320T170000
34
- RRULE:FREQ=DAILY;BYHOUR=17;BYMINUTE=0;COUNT=5
35
- */
36
-
37
- // all() returns an array of Temporal.ZonedDateTime:
38
- const dates = rule.all();
39
- dates.forEach(dt => console.log(dt.toString()));
40
- // [
41
- // "2025-03-20T17:00:00[America/Chicago]",
42
- // "2025-03-21T17:00:00[America/Chicago]",
43
- // // … total of 5 days
44
- // ]
45
- ```
46
-
47
- ## 2. Enumerate occurrences in a time window
20
+ Parse an ICS snippet and enumerate the occurrences:
48
21
 
49
22
  ```typescript
23
+ import { RRuleTemporal } from "rrule-temporal";
50
24
 
51
- const ics = `DTSTART;TZID=America/Chicago:20250401T000000
52
- RRULE:FREQ=DAILY;BYHOUR=0;BYMINUTE=0;UNTIL=20250405T000000Z`.trim();
53
- const rule = new RRuleTemporal({ rruleString: ics });
54
- const start = new Date(Date.UTC(2025, 3, 2, 0, 0)); // Apr 2 00:00 UTC
55
- // after:
56
- const end = new Date(
57
- // 2025-04-04 00:00 America/Chicago → 05:00 UTC
58
- Date.UTC(2025, 3, 4, 5, 0, 0)
59
- );
60
-
61
- test("between returns occurrences in window inclusive/exclusive", () => {
62
- const arrExc = rule.between(start, end, false);
63
- expect(arrExc.map((d) => d.day)).toEqual([2, 3]);
25
+ const rule = new RRuleTemporal({
26
+ rruleString: `DTSTART;TZID=UTC:20250101T090000\nRRULE:FREQ=DAILY;COUNT=3`
27
+ });
64
28
 
65
- const arrInc = rule.between(start, end, true);
66
- expect(arrInc.map((d) => d.day)).toEqual([2, 3, 4]);
67
- });
68
- ```
29
+ rule.all().forEach(dt => console.log(dt.toString()));
30
+ // 2025-01-01T09:00:00[UTC]
31
+ // 2025-01-02T09:00:00[UTC]
32
+ // 2025-01-03T09:00:00[UTC]
33
+ ```
69
34
 
70
- ## 3. Manual options
35
+ ## Creating a rule with options
71
36
 
72
- Build a rule from explicit options, overriding start time and interval:
37
+ Instead of a full ICS string you can supply the recurrence parameters directly:
73
38
 
74
39
  ```typescript
75
- // Every 2 days at 09:15 America/Chicago, 3 occurrences, starting 2025-04-20 08:30 CT
76
- const dtstart = Temporal.ZonedDateTime.from({
77
- year: 2025, month: 4, day: 20,
78
- hour: 8, minute: 30,
79
- timeZone: "America/Chicago"
80
- });
40
+ import { Temporal } from "@js-temporal/polyfill";
81
41
 
82
42
  const rule = new RRuleTemporal({
83
- freq: "DAILY",
43
+ freq: "DAILY",
84
44
  interval: 2,
85
- count: 3,
86
- byHour: [9],
45
+ count: 3,
46
+ byHour: [9],
87
47
  byMinute: [15],
88
- dtstart,
89
- tzid: "America/Chicago",
48
+ tzid: "America/Chicago",
49
+ dtstart: Temporal.ZonedDateTime.from({
50
+ year: 2025, month: 4, day: 20,
51
+ hour: 8, minute: 30,
52
+ timeZone: "America/Chicago"
53
+ })
90
54
  });
91
55
 
92
- rule.all().forEach((dt, i) => {
93
- console.log(i, dt.toString());
94
- });
95
- // 0 "2025-04-20T09:15:00[America/Chicago]"
96
- // 1 "2025-04-22T09:15:00[America/Chicago]"
97
- // 2 "2025-04-24T09:15:00[America/Chicago]"
56
+ rule.all().forEach(dt => console.log(dt.toString()));
98
57
  ```
99
58
 
100
- ## 4. Windowed queries with between()
59
+ ## Querying occurrences
101
60
 
102
- Fetch occurrences in a given time window, with inclusive/exclusive end:
103
- ```typescript
104
- // Daily at 00:00 CT until 2025-04-05T00:00Z inclusive
105
- const ics2 = `
106
- DTSTART;TZID=America/Chicago:20250401T000000
107
- RRULE:FREQ=DAILY;BYHOUR=0;BYMINUTE=0;UNTIL=20250405T000000Z
108
- `.trim();
109
-
110
- const rule2 = new RRuleTemporal({ rruleString: ics2 });
61
+ Use the provided methods to enumerate or search for occurrences:
111
62
 
112
- // Define UTC window: from 2025-04-02 00:00 UTC through 2025-04-04 05:00 UTC
63
+ ```typescript
64
+ // Get all events within a window
113
65
  const start = new Date(Date.UTC(2025, 3, 2, 0, 0));
114
- const end = new Date(Date.UTC(2025, 3, 4, 5, 0));
66
+ const end = new Date(Date.UTC(2025, 3, 4, 5, 0));
67
+ const hits = rule.between(start, end, true);
115
68
 
116
- console.log(rule2.between(start, end, false).map(d => d.toString()));
117
- // [
118
- // "2025-04-02T00:00:00[America/Chicago]",
119
- // "2025-04-03T00:00:00[America/Chicago]"
120
- // ]
121
-
122
- console.log(rule2.between(start, end, true).map(d => d.toString()));
123
- // adds "2025-04-04T00:00:00[America/Chicago]"
69
+ // Next and previous occurrences
70
+ const next = rule.next();
71
+ const prev = rule.previous(new Date("2025-05-01T00:00Z"));
124
72
  ```
125
73
 
126
- ## 5. Next/previous occurrence
127
-
128
- Find the next or previous occurrence relative to any date:
74
+ ## Converting back to text
129
75
 
130
76
  ```typescript
131
- // Monthly at 12:00 America/Chicago, 12 total
132
- const ics3 = `
133
- DTSTART;TZID=America/Chicago:20250101T120000
134
- RRULE:FREQ=MONTHLY;BYHOUR=12;BYMINUTE=0;COUNT=12
135
- `.trim();
136
-
137
- const rule3 = new RRuleTemporal({ rruleString: ics3 });
138
-
139
- // Next occurrence after the current time in Central Time
140
- // Where hour and minute conditions are met
141
- const firstOccurrence = rule.next(
142
- Temporal.Now.zonedDateTimeISO("America/Chicago")
143
- );
144
-
145
- // Next after 2025-03-15T00:00:00Z
146
- const nxt = rule3.next(new Date("2025-03-15T00:00:00Z"));
147
- console.log(nxt?.toString()); // "2025-04-01T12:00:00[UTC]"
148
-
149
- // Previous on or before 2025-06-05T00:00:00Z
150
- const prev = rule3.previous(new Date("2025-06-05T00:00:00Z"), true);
151
- console.log(prev?.toString()); // "2025-06-01T12:00:00[UTC]"
77
+ rule.toString(); // DTSTART and RRULE lines
78
+ rule.toText(); // human readable description
152
79
  ```
153
80
 
154
- ## 6. toString()
81
+ ## API
155
82
 
156
- Convert the rule back to an ICS string:
83
+ | Method | Description |
84
+ | ------ | ----------- |
85
+ | `new RRuleTemporal(opts)` | Create a rule from an ICS snippet or manual options. |
86
+ | `all(iterator?)` | Return every occurrence. When the rule has no end the optional iterator is required. |
87
+ | `between(after, before, inclusive?)` | Occurrences within a time range. |
88
+ | `next(after?, inclusive?)` | Next occurrence after a given date. |
89
+ | `previous(before?, inclusive?)` | Previous occurrence before a date. |
90
+ | `toString()` | Convert the rule back into `DTSTART` and `RRULE` lines. |
91
+ | `toText(formatter?)` | English description of the rule. |
92
+ | `options()` | Return the normalized options object. |
157
93
 
158
- ```typescript
159
- console.log(rule.toString());
160
- // DTSTART;TZID=America/Chicago:20250320T170000
161
- // RRULE:FREQ=DAILY;BYHOUR=17;BYMINUTE=0;COUNT=5
162
- ```
94
+ ## Further examples
163
95
 
164
- ## 7. BYDAY/BYMONTH examples:
96
+ Enumerating weekdays within a month or rotating through months can be achieved
97
+ with the more advanced RFC 5545 fields:
165
98
 
166
99
  ```typescript
167
- // 2nd & 4th Fridays each month at 00:00 CT, first 6 occurrences
168
- const ics4 = `
169
- DTSTART;TZID=America/Chicago:20250325T000000
170
- RRULE:FREQ=MONTHLY;BYDAY=2FR,4FR;BYHOUR=0;BYMINUTE=0;COUNT=6
171
- `.trim();
172
-
173
- const rule4 = new RRuleTemporal({ rruleString: ics4 });
174
- rule4.all().forEach(dt => console.log(dt.toString()));
175
- // [
176
- // "2025-04-11T00:00:00[America/Chicago]",
177
- // "2025-04-25T00:00:00[America/Chicago]",
178
- // "2025-05-09T00:00:00[America/Chicago]",
179
- // …
180
- ]
181
-
182
- // Yearly rotated through Jan, Jun, Dec at 09:00 UTC, 4 occurrences
183
- const dtstart5 = Temporal.ZonedDateTime.from({
100
+ // 2nd & 4th Fridays each month at midnight CT, first 6 occurrences
101
+ const ruleA = new RRuleTemporal({
102
+ rruleString: `DTSTART;TZID=America/Chicago:20250325T000000\nRRULE:FREQ=MONTHLY;BYDAY=2FR,4FR;BYHOUR=0;BYMINUTE=0;COUNT=6`
103
+ });
104
+ ruleA.all().forEach(dt => console.log(dt.toString()));
105
+
106
+ // Rotate yearly through Jan, Jun and Dec at 09:00 UTC
107
+ const dtstart = Temporal.ZonedDateTime.from({
184
108
  year: 2025, month: 1, day: 10, hour: 9, minute: 0, timeZone: "UTC"
185
109
  });
186
- const rule5 = new RRuleTemporal({
187
- freq: "YEARLY",
110
+ const ruleB = new RRuleTemporal({
111
+ freq: "YEARLY",
188
112
  interval: 1,
189
- count: 4,
190
- byMonth: [1, 6, 12],
191
- byHour: [9],
113
+ count: 4,
114
+ byMonth: [1, 6, 12],
115
+ byHour: [9],
192
116
  byMinute: [0],
193
- dtstart: dtstart5
117
+ dtstart
194
118
  });
195
- rule5.all().forEach(dt => console.log(dt.toString()));
196
- // [
197
- // "2025-01-10T09:00:00[UTC]",
198
- // "2026-06-10T09:00:00[UTC]",
199
- // "2027-12-10T09:00:00[UTC]",
200
- // "2028-01-10T09:00:00[UTC]"
201
- // ]
119
+ ruleB.all().forEach(dt => console.log(dt.toString()));
202
120
  ```
203
-
package/dist/index.cjs CHANGED
@@ -24,6 +24,60 @@ __export(index_exports, {
24
24
  });
25
25
  module.exports = __toCommonJS(index_exports);
26
26
  var import_polyfill = require("@js-temporal/polyfill");
27
+ var WEEKDAY_NAMES = [
28
+ "Monday",
29
+ "Tuesday",
30
+ "Wednesday",
31
+ "Thursday",
32
+ "Friday",
33
+ "Saturday",
34
+ "Sunday"
35
+ ];
36
+ var MONTH_NAMES = [
37
+ "January",
38
+ "February",
39
+ "March",
40
+ "April",
41
+ "May",
42
+ "June",
43
+ "July",
44
+ "August",
45
+ "September",
46
+ "October",
47
+ "November",
48
+ "December"
49
+ ];
50
+ var defaultDateFormatter = (year, month, day) => `${month} ${day}, ${year}`;
51
+ function ordinal(n) {
52
+ const abs = Math.abs(n);
53
+ const suffix = abs % 10 === 1 && abs % 100 !== 11 ? "st" : abs % 10 === 2 && abs % 100 !== 12 ? "nd" : abs % 10 === 3 && abs % 100 !== 13 ? "rd" : "th";
54
+ return n < 0 ? `last` : `${abs}${suffix}`;
55
+ }
56
+ function list(arr, mapFn = (x) => `${x}`, final = "and") {
57
+ const mapped = arr.map(mapFn);
58
+ if (mapped.length === 1) return mapped[0];
59
+ return mapped.slice(0, -1).join(", ") + ` ${final} ` + mapped[mapped.length - 1];
60
+ }
61
+ function formatByDayToken(tok) {
62
+ if (typeof tok === "number") return tok.toString();
63
+ const m = tok.match(/^([+-]?\d+)?(MO|TU|WE|TH|FR|SA|SU)$/);
64
+ if (!m) return tok;
65
+ const ord = m[1] ? parseInt(m[1], 10) : 0;
66
+ const weekdayMap = {
67
+ MO: 0,
68
+ TU: 1,
69
+ WE: 2,
70
+ TH: 3,
71
+ FR: 4,
72
+ SA: 5,
73
+ SU: 6
74
+ };
75
+ const idx = weekdayMap[m[2]];
76
+ const name = WEEKDAY_NAMES[idx];
77
+ if (ord === 0) return name;
78
+ if (ord === -1) return `last ${name}`;
79
+ return `${ordinal(ord)} ${name}`;
80
+ }
27
81
  function parseRRuleString(input, fallbackDtstart) {
28
82
  let dtstart;
29
83
  let tzid = "UTC";
@@ -83,10 +137,30 @@ function parseRRuleString(input, fallbackDtstart) {
83
137
  case "BYMONTH":
84
138
  opts.byMonth = val.split(",").map((n) => parseInt(n, 10));
85
139
  break;
140
+ case "BYMONTHDAY":
141
+ opts.byMonthDay = val.split(",").map((n) => parseInt(n, 10));
142
+ break;
86
143
  }
87
144
  }
88
145
  return opts;
89
146
  }
147
+ function formatTime(hour, minute = 0) {
148
+ const hr12 = (hour + 11) % 12 + 1;
149
+ const ampm = hour < 12 ? "AM" : "PM";
150
+ if (minute) {
151
+ return `${hr12}:${String(minute).padStart(2, "0")} ${ampm}`;
152
+ }
153
+ return `${hr12} ${ampm}`;
154
+ }
155
+ function tzAbbreviation(zdt) {
156
+ const parts = new Intl.DateTimeFormat("en-US", {
157
+ timeZone: zdt.timeZoneId,
158
+ timeZoneName: "short",
159
+ hour: "numeric"
160
+ }).formatToParts(new Date(zdt.epochMilliseconds));
161
+ const tzPart = parts.find((p) => p.type === "timeZoneName");
162
+ return tzPart?.value || zdt.timeZoneId;
163
+ }
90
164
  var RRuleTemporal = class {
91
165
  tzid;
92
166
  originalDtstart;
@@ -178,9 +252,14 @@ var RRuleTemporal = class {
178
252
  SA: 6,
179
253
  SU: 7
180
254
  };
181
- const targetDow = dayMap[this.opts.byDay[0]];
182
- const delta = (targetDow - zdt.dayOfWeek + 7) % 7;
183
- zdt = zdt.add({ days: delta });
255
+ const deltas = this.opts.byDay.map((tok) => {
256
+ const wdTok = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)?.[1];
257
+ return wdTok ? (dayMap[wdTok] - zdt.dayOfWeek + 7) % 7 : null;
258
+ }).filter((d) => d !== null);
259
+ if (deltas.length) {
260
+ const delta = Math.min(...deltas);
261
+ zdt = zdt.add({ days: delta });
262
+ }
184
263
  }
185
264
  const { byHour, byMinute } = this.opts;
186
265
  if (byHour || byMinute) {
@@ -239,7 +318,6 @@ var RRuleTemporal = class {
239
318
  if (zdt.dayOfWeek === wd) return true;
240
319
  continue;
241
320
  }
242
- const year = zdt.year;
243
321
  const month = zdt.month;
244
322
  let dt = zdt.with({ day: 1 });
245
323
  const candidates = [];
@@ -257,8 +335,16 @@ var RRuleTemporal = class {
257
335
  if (!byMonth) return true;
258
336
  return byMonth.includes(zdt.month);
259
337
  }
338
+ matchesByMonthDay(zdt) {
339
+ const { byMonthDay } = this.opts;
340
+ if (!byMonthDay) return true;
341
+ const lastDay = zdt.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
342
+ return byMonthDay.some(
343
+ (d) => d > 0 ? zdt.day === d : zdt.day === lastDay + d + 1
344
+ );
345
+ }
260
346
  matchesAll(zdt) {
261
- return this.matchesByDay(zdt) && this.matchesByMonth(zdt);
347
+ return this.matchesByDay(zdt) && this.matchesByMonth(zdt) && this.matchesByMonthDay(zdt);
262
348
  }
263
349
  options() {
264
350
  return this.opts;
@@ -273,7 +359,7 @@ var RRuleTemporal = class {
273
359
  throw new Error("all() requires iterator when no COUNT/UNTIL");
274
360
  }
275
361
  const dates = [];
276
- if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
362
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
277
363
  const start = this.originalDtstart;
278
364
  let monthCursor = start.with({ day: 1 });
279
365
  let matchCount2 = 0;
@@ -347,7 +433,7 @@ var RRuleTemporal = class {
347
433
  }
348
434
  return dates;
349
435
  }
350
- if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
436
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
351
437
  const start = this.originalDtstart;
352
438
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
353
439
  let i = 0;
@@ -374,6 +460,30 @@ var RRuleTemporal = class {
374
460
  }
375
461
  return dates;
376
462
  }
463
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
464
+ const start = this.originalDtstart;
465
+ let yearCursor = start.with({ month: 1, day: 1 });
466
+ let matchCount2 = 0;
467
+ outer_year: while (true) {
468
+ const occs = this.generateYearlyOccurrences(yearCursor);
469
+ for (const occ of occs) {
470
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
471
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
472
+ break outer_year;
473
+ }
474
+ if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
475
+ break outer_year;
476
+ }
477
+ if (iterator && !iterator(occ, matchCount2)) {
478
+ break outer_year;
479
+ }
480
+ dates.push(occ);
481
+ matchCount2++;
482
+ }
483
+ yearCursor = yearCursor.add({ years: this.opts.interval });
484
+ }
485
+ return dates;
486
+ }
377
487
  let current = this.computeFirst();
378
488
  let matchCount = 0;
379
489
  while (true) {
@@ -405,7 +515,7 @@ var RRuleTemporal = class {
405
515
  const startInst = after instanceof Date ? import_polyfill.Temporal.Instant.from(after.toISOString()) : after.toInstant();
406
516
  const endInst = before instanceof Date ? import_polyfill.Temporal.Instant.from(before.toISOString()) : before.toInstant();
407
517
  const results = [];
408
- if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
518
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
409
519
  let monthCursor = this.computeFirst().with({ day: 1 });
410
520
  outer: while (true) {
411
521
  const occs = this.generateMonthlyOccurrences(monthCursor);
@@ -422,7 +532,7 @@ var RRuleTemporal = class {
422
532
  }
423
533
  return results;
424
534
  }
425
- if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
535
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
426
536
  const start = this.originalDtstart;
427
537
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
428
538
  let i = 0;
@@ -442,6 +552,24 @@ var RRuleTemporal = class {
442
552
  }
443
553
  return results;
444
554
  }
555
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
556
+ const start = this.originalDtstart;
557
+ let yearCursor = start.with({ month: 1, day: 1 });
558
+ outer_year: while (true) {
559
+ const occs = this.generateYearlyOccurrences(yearCursor);
560
+ for (const occ of occs) {
561
+ const inst = occ.toInstant();
562
+ if (inc ? import_polyfill.Temporal.Instant.compare(inst, endInst) > 0 : import_polyfill.Temporal.Instant.compare(inst, endInst) >= 0) {
563
+ break outer_year;
564
+ }
565
+ if (import_polyfill.Temporal.Instant.compare(inst, startInst) >= 0) {
566
+ results.push(occ);
567
+ }
568
+ }
569
+ yearCursor = yearCursor.add({ years: this.opts.interval });
570
+ }
571
+ return results;
572
+ }
445
573
  if (this.opts.freq === "WEEKLY") {
446
574
  const startInst2 = after instanceof Date ? import_polyfill.Temporal.Instant.from(after.toISOString()) : after.toInstant();
447
575
  const endInst2 = before instanceof Date ? import_polyfill.Temporal.Instant.from(before.toISOString()) : before.toInstant();
@@ -532,24 +660,123 @@ var RRuleTemporal = class {
532
660
  const iso = this.originalDtstart.toString({ smallestUnit: "second" }).replace(/[-:]/g, "");
533
661
  const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
534
662
  const parts = [];
535
- const { freq, interval, count, byHour, byMinute, byDay, byMonth } = this.opts;
663
+ const {
664
+ freq,
665
+ interval,
666
+ count,
667
+ until,
668
+ byHour,
669
+ byMinute,
670
+ byDay,
671
+ byMonth,
672
+ byMonthDay
673
+ } = this.opts;
536
674
  parts.push(`FREQ=${freq}`);
537
675
  if (interval !== 1) parts.push(`INTERVAL=${interval}`);
538
676
  if (count !== void 0) parts.push(`COUNT=${count}`);
677
+ if (until) {
678
+ const u = until.toInstant().toString().replace(/[-:]/g, "");
679
+ parts.push(`UNTIL=${u.slice(0, 15)}Z`);
680
+ }
539
681
  if (byHour) parts.push(`BYHOUR=${byHour.join(",")}`);
540
682
  if (byMinute) parts.push(`BYMINUTE=${byMinute.join(",")}`);
541
683
  if (byDay) parts.push(`BYDAY=${byDay.join(",")}`);
542
684
  if (byMonth) parts.push(`BYMONTH=${byMonth.join(",")}`);
685
+ if (byMonthDay) parts.push(`BYMONTHDAY=${byMonthDay.join(",")}`);
543
686
  return [dtLine, `RRULE:${parts.join(";")}`].join("\n");
544
687
  }
688
+ /**
689
+ * Convert this rule to a human readable English description.
690
+ */
691
+ toText(formatter = defaultDateFormatter) {
692
+ const {
693
+ freq,
694
+ interval = 1,
695
+ count,
696
+ until,
697
+ byDay,
698
+ byHour,
699
+ byMinute,
700
+ byMonth,
701
+ byMonthDay
702
+ } = this.opts;
703
+ const parts = ["every"];
704
+ const base = {
705
+ YEARLY: "year",
706
+ MONTHLY: "month",
707
+ WEEKLY: "week",
708
+ DAILY: "day",
709
+ HOURLY: "hour",
710
+ MINUTELY: "minute",
711
+ SECONDLY: "second"
712
+ }[freq];
713
+ const daysNormalized = byDay?.map((d) => d.toUpperCase());
714
+ const isWeekdays = daysNormalized && daysNormalized.length === 5 && ["MO", "TU", "WE", "TH", "FR"].every((d) => daysNormalized.includes(d));
715
+ const isEveryday = daysNormalized && daysNormalized.length === 7 && ["MO", "TU", "WE", "TH", "FR", "SA", "SU"].every(
716
+ (d) => daysNormalized.includes(d)
717
+ );
718
+ if (freq === "WEEKLY" && interval === 1 && isWeekdays) {
719
+ parts.push("weekday");
720
+ } else if (freq === "WEEKLY" && interval === 1 && isEveryday) {
721
+ parts.push("day");
722
+ } else {
723
+ if (interval !== 1) {
724
+ parts.push(interval.toString(), base + "s");
725
+ } else {
726
+ parts.push(base);
727
+ }
728
+ }
729
+ if (freq === "WEEKLY" && byDay && !isWeekdays && !isEveryday) {
730
+ parts.push("on", list(byDay, formatByDayToken));
731
+ } else if (byDay && freq !== "WEEKLY") {
732
+ parts.push("on", list(byDay, formatByDayToken));
733
+ }
734
+ if (byMonth) {
735
+ parts.push(
736
+ "in",
737
+ list(byMonth, (m) => MONTH_NAMES[m - 1])
738
+ );
739
+ }
740
+ if (byMonthDay) {
741
+ parts.push(
742
+ "on the",
743
+ list(byMonthDay, (d) => ordinal(d)),
744
+ "day of the month"
745
+ );
746
+ }
747
+ if (byHour) {
748
+ const minutes = byMinute ?? [0];
749
+ const times = byHour.flatMap((h) => minutes.map((m) => formatTime(h, m)));
750
+ parts.push("at", list(times));
751
+ parts.push(tzAbbreviation(this.originalDtstart));
752
+ }
753
+ if (until) {
754
+ parts.push(
755
+ "until",
756
+ formatter(until.year, MONTH_NAMES[until.month - 1], until.day)
757
+ );
758
+ } else if (count !== void 0) {
759
+ parts.push("for", count.toString(), count === 1 ? "time" : "times");
760
+ }
761
+ return parts.join(" ");
762
+ }
545
763
  /**
546
764
  * Given any date in a month, return all the ZonedDateTimes in that month
547
765
  * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
548
766
  */
549
767
  generateMonthlyOccurrences(sample) {
550
- const { byDay, byMonth, tzid } = this.opts;
768
+ const { byDay, byMonth, byMonthDay } = this.opts;
551
769
  if (byMonth && !byMonth.includes(sample.month)) return [];
552
- if (!byDay || byDay.length === 0) {
770
+ const lastDay = sample.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
771
+ let byMonthDayHits = [];
772
+ if (byMonthDay && byMonthDay.length > 0) {
773
+ byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
774
+ }
775
+ if (!byDay && byMonthDayHits.length) {
776
+ const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
777
+ return dates.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
778
+ }
779
+ if (!byDay) {
553
780
  return this.expandByHourMinute(sample);
554
781
  }
555
782
  const dayMap = {
@@ -573,20 +800,38 @@ var RRuleTemporal = class {
573
800
  (buckets[dow] ||= []).push(cursor.day);
574
801
  cursor = cursor.add({ days: 1 });
575
802
  }
576
- const hits = [];
803
+ const byDayHits = [];
577
804
  for (const { ord, wd } of tokens) {
578
- const list = buckets[wd] ?? [];
579
- if (!list.length) continue;
805
+ const list2 = buckets[wd] ?? [];
806
+ if (!list2.length) continue;
580
807
  if (ord === 0) {
581
- for (const d of list) hits.push(sample.with({ day: d }));
808
+ for (const d of list2) byDayHits.push(d);
582
809
  } else {
583
- const idx = ord > 0 ? ord - 1 : list.length + ord;
584
- const dayN = list[idx];
585
- if (dayN) hits.push(sample.with({ day: dayN }));
810
+ const idx = ord > 0 ? ord - 1 : list2.length + ord;
811
+ const dayN = list2[idx];
812
+ if (dayN) byDayHits.push(dayN);
586
813
  }
587
814
  }
815
+ let finalDays = byDayHits;
816
+ if (byMonthDayHits.length) {
817
+ finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
818
+ }
819
+ const hits = finalDays.map((d) => sample.with({ day: d }));
588
820
  return hits.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
589
821
  }
822
+ /**
823
+ * Given any date in a year, return all ZonedDateTimes in that year matching
824
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
825
+ * if BYMONTH is not specified.
826
+ */
827
+ generateYearlyOccurrences(sample) {
828
+ const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : [this.originalDtstart.month];
829
+ const occs = months.flatMap((m) => {
830
+ const monthSample = sample.with({ month: m, day: 1 });
831
+ return this.generateMonthlyOccurrences(monthSample);
832
+ });
833
+ return occs.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
834
+ }
590
835
  };
591
836
  // Annotate the CommonJS export names for ESM import in node:
592
837
  0 && (module.exports = {
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Temporal } from '@js-temporal/polyfill';
2
2
 
3
+ type DateFormatter = (year: number, month: string, day: number) => string;
3
4
  type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
4
5
  interface BaseOpts {
5
6
  tzid?: string;
@@ -13,12 +14,13 @@ interface ManualOpts extends BaseOpts {
13
14
  byMinute?: number[];
14
15
  byDay?: string[];
15
16
  byMonth?: number[];
17
+ byMonthDay?: number[];
16
18
  dtstart: Temporal.ZonedDateTime;
17
19
  }
18
20
  interface IcsOpts extends BaseOpts {
19
21
  rruleString: string;
20
22
  }
21
- type RRuleOpts = ManualOpts | IcsOpts;
23
+ type RRuleOptions = ManualOpts | IcsOpts;
22
24
  declare class RRuleTemporal {
23
25
  private tzid;
24
26
  private originalDtstart;
@@ -38,6 +40,7 @@ declare class RRuleTemporal {
38
40
  private generateWeeklyOccurrences;
39
41
  private matchesByDay;
40
42
  private matchesByMonth;
43
+ private matchesByMonthDay;
41
44
  private matchesAll;
42
45
  options(): ManualOpts;
43
46
  /**
@@ -69,11 +72,21 @@ declare class RRuleTemporal {
69
72
  */
70
73
  previous(before?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
71
74
  toString(): string;
75
+ /**
76
+ * Convert this rule to a human readable English description.
77
+ */
78
+ toText(formatter?: DateFormatter): string;
72
79
  /**
73
80
  * Given any date in a month, return all the ZonedDateTimes in that month
74
81
  * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
75
82
  */
76
83
  private generateMonthlyOccurrences;
84
+ /**
85
+ * Given any date in a year, return all ZonedDateTimes in that year matching
86
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
87
+ * if BYMONTH is not specified.
88
+ */
89
+ private generateYearlyOccurrences;
77
90
  }
78
91
 
79
- export { type RRuleOpts, RRuleTemporal };
92
+ export { type DateFormatter, type RRuleOptions, RRuleTemporal };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Temporal } from '@js-temporal/polyfill';
2
2
 
3
+ type DateFormatter = (year: number, month: string, day: number) => string;
3
4
  type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
4
5
  interface BaseOpts {
5
6
  tzid?: string;
@@ -13,12 +14,13 @@ interface ManualOpts extends BaseOpts {
13
14
  byMinute?: number[];
14
15
  byDay?: string[];
15
16
  byMonth?: number[];
17
+ byMonthDay?: number[];
16
18
  dtstart: Temporal.ZonedDateTime;
17
19
  }
18
20
  interface IcsOpts extends BaseOpts {
19
21
  rruleString: string;
20
22
  }
21
- type RRuleOpts = ManualOpts | IcsOpts;
23
+ type RRuleOptions = ManualOpts | IcsOpts;
22
24
  declare class RRuleTemporal {
23
25
  private tzid;
24
26
  private originalDtstart;
@@ -38,6 +40,7 @@ declare class RRuleTemporal {
38
40
  private generateWeeklyOccurrences;
39
41
  private matchesByDay;
40
42
  private matchesByMonth;
43
+ private matchesByMonthDay;
41
44
  private matchesAll;
42
45
  options(): ManualOpts;
43
46
  /**
@@ -69,11 +72,21 @@ declare class RRuleTemporal {
69
72
  */
70
73
  previous(before?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
71
74
  toString(): string;
75
+ /**
76
+ * Convert this rule to a human readable English description.
77
+ */
78
+ toText(formatter?: DateFormatter): string;
72
79
  /**
73
80
  * Given any date in a month, return all the ZonedDateTimes in that month
74
81
  * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
75
82
  */
76
83
  private generateMonthlyOccurrences;
84
+ /**
85
+ * Given any date in a year, return all ZonedDateTimes in that year matching
86
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
87
+ * if BYMONTH is not specified.
88
+ */
89
+ private generateYearlyOccurrences;
77
90
  }
78
91
 
79
- export { type RRuleOpts, RRuleTemporal };
92
+ export { type DateFormatter, type RRuleOptions, RRuleTemporal };
package/dist/index.js CHANGED
@@ -1,5 +1,59 @@
1
1
  // src/index.ts
2
2
  import { Temporal } from "@js-temporal/polyfill";
3
+ var WEEKDAY_NAMES = [
4
+ "Monday",
5
+ "Tuesday",
6
+ "Wednesday",
7
+ "Thursday",
8
+ "Friday",
9
+ "Saturday",
10
+ "Sunday"
11
+ ];
12
+ var MONTH_NAMES = [
13
+ "January",
14
+ "February",
15
+ "March",
16
+ "April",
17
+ "May",
18
+ "June",
19
+ "July",
20
+ "August",
21
+ "September",
22
+ "October",
23
+ "November",
24
+ "December"
25
+ ];
26
+ var defaultDateFormatter = (year, month, day) => `${month} ${day}, ${year}`;
27
+ function ordinal(n) {
28
+ const abs = Math.abs(n);
29
+ const suffix = abs % 10 === 1 && abs % 100 !== 11 ? "st" : abs % 10 === 2 && abs % 100 !== 12 ? "nd" : abs % 10 === 3 && abs % 100 !== 13 ? "rd" : "th";
30
+ return n < 0 ? `last` : `${abs}${suffix}`;
31
+ }
32
+ function list(arr, mapFn = (x) => `${x}`, final = "and") {
33
+ const mapped = arr.map(mapFn);
34
+ if (mapped.length === 1) return mapped[0];
35
+ return mapped.slice(0, -1).join(", ") + ` ${final} ` + mapped[mapped.length - 1];
36
+ }
37
+ function formatByDayToken(tok) {
38
+ if (typeof tok === "number") return tok.toString();
39
+ const m = tok.match(/^([+-]?\d+)?(MO|TU|WE|TH|FR|SA|SU)$/);
40
+ if (!m) return tok;
41
+ const ord = m[1] ? parseInt(m[1], 10) : 0;
42
+ const weekdayMap = {
43
+ MO: 0,
44
+ TU: 1,
45
+ WE: 2,
46
+ TH: 3,
47
+ FR: 4,
48
+ SA: 5,
49
+ SU: 6
50
+ };
51
+ const idx = weekdayMap[m[2]];
52
+ const name = WEEKDAY_NAMES[idx];
53
+ if (ord === 0) return name;
54
+ if (ord === -1) return `last ${name}`;
55
+ return `${ordinal(ord)} ${name}`;
56
+ }
3
57
  function parseRRuleString(input, fallbackDtstart) {
4
58
  let dtstart;
5
59
  let tzid = "UTC";
@@ -59,10 +113,30 @@ function parseRRuleString(input, fallbackDtstart) {
59
113
  case "BYMONTH":
60
114
  opts.byMonth = val.split(",").map((n) => parseInt(n, 10));
61
115
  break;
116
+ case "BYMONTHDAY":
117
+ opts.byMonthDay = val.split(",").map((n) => parseInt(n, 10));
118
+ break;
62
119
  }
63
120
  }
64
121
  return opts;
65
122
  }
123
+ function formatTime(hour, minute = 0) {
124
+ const hr12 = (hour + 11) % 12 + 1;
125
+ const ampm = hour < 12 ? "AM" : "PM";
126
+ if (minute) {
127
+ return `${hr12}:${String(minute).padStart(2, "0")} ${ampm}`;
128
+ }
129
+ return `${hr12} ${ampm}`;
130
+ }
131
+ function tzAbbreviation(zdt) {
132
+ const parts = new Intl.DateTimeFormat("en-US", {
133
+ timeZone: zdt.timeZoneId,
134
+ timeZoneName: "short",
135
+ hour: "numeric"
136
+ }).formatToParts(new Date(zdt.epochMilliseconds));
137
+ const tzPart = parts.find((p) => p.type === "timeZoneName");
138
+ return tzPart?.value || zdt.timeZoneId;
139
+ }
66
140
  var RRuleTemporal = class {
67
141
  tzid;
68
142
  originalDtstart;
@@ -154,9 +228,14 @@ var RRuleTemporal = class {
154
228
  SA: 6,
155
229
  SU: 7
156
230
  };
157
- const targetDow = dayMap[this.opts.byDay[0]];
158
- const delta = (targetDow - zdt.dayOfWeek + 7) % 7;
159
- zdt = zdt.add({ days: delta });
231
+ const deltas = this.opts.byDay.map((tok) => {
232
+ const wdTok = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)?.[1];
233
+ return wdTok ? (dayMap[wdTok] - zdt.dayOfWeek + 7) % 7 : null;
234
+ }).filter((d) => d !== null);
235
+ if (deltas.length) {
236
+ const delta = Math.min(...deltas);
237
+ zdt = zdt.add({ days: delta });
238
+ }
160
239
  }
161
240
  const { byHour, byMinute } = this.opts;
162
241
  if (byHour || byMinute) {
@@ -215,7 +294,6 @@ var RRuleTemporal = class {
215
294
  if (zdt.dayOfWeek === wd) return true;
216
295
  continue;
217
296
  }
218
- const year = zdt.year;
219
297
  const month = zdt.month;
220
298
  let dt = zdt.with({ day: 1 });
221
299
  const candidates = [];
@@ -233,8 +311,16 @@ var RRuleTemporal = class {
233
311
  if (!byMonth) return true;
234
312
  return byMonth.includes(zdt.month);
235
313
  }
314
+ matchesByMonthDay(zdt) {
315
+ const { byMonthDay } = this.opts;
316
+ if (!byMonthDay) return true;
317
+ const lastDay = zdt.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
318
+ return byMonthDay.some(
319
+ (d) => d > 0 ? zdt.day === d : zdt.day === lastDay + d + 1
320
+ );
321
+ }
236
322
  matchesAll(zdt) {
237
- return this.matchesByDay(zdt) && this.matchesByMonth(zdt);
323
+ return this.matchesByDay(zdt) && this.matchesByMonth(zdt) && this.matchesByMonthDay(zdt);
238
324
  }
239
325
  options() {
240
326
  return this.opts;
@@ -249,7 +335,7 @@ var RRuleTemporal = class {
249
335
  throw new Error("all() requires iterator when no COUNT/UNTIL");
250
336
  }
251
337
  const dates = [];
252
- if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
338
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
253
339
  const start = this.originalDtstart;
254
340
  let monthCursor = start.with({ day: 1 });
255
341
  let matchCount2 = 0;
@@ -323,7 +409,7 @@ var RRuleTemporal = class {
323
409
  }
324
410
  return dates;
325
411
  }
326
- if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
412
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
327
413
  const start = this.originalDtstart;
328
414
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
329
415
  let i = 0;
@@ -350,6 +436,30 @@ var RRuleTemporal = class {
350
436
  }
351
437
  return dates;
352
438
  }
439
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
440
+ const start = this.originalDtstart;
441
+ let yearCursor = start.with({ month: 1, day: 1 });
442
+ let matchCount2 = 0;
443
+ outer_year: while (true) {
444
+ const occs = this.generateYearlyOccurrences(yearCursor);
445
+ for (const occ of occs) {
446
+ if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
447
+ if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
448
+ break outer_year;
449
+ }
450
+ if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
451
+ break outer_year;
452
+ }
453
+ if (iterator && !iterator(occ, matchCount2)) {
454
+ break outer_year;
455
+ }
456
+ dates.push(occ);
457
+ matchCount2++;
458
+ }
459
+ yearCursor = yearCursor.add({ years: this.opts.interval });
460
+ }
461
+ return dates;
462
+ }
353
463
  let current = this.computeFirst();
354
464
  let matchCount = 0;
355
465
  while (true) {
@@ -381,7 +491,7 @@ var RRuleTemporal = class {
381
491
  const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
382
492
  const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
383
493
  const results = [];
384
- if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
494
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
385
495
  let monthCursor = this.computeFirst().with({ day: 1 });
386
496
  outer: while (true) {
387
497
  const occs = this.generateMonthlyOccurrences(monthCursor);
@@ -398,7 +508,7 @@ var RRuleTemporal = class {
398
508
  }
399
509
  return results;
400
510
  }
401
- if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
511
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
402
512
  const start = this.originalDtstart;
403
513
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
404
514
  let i = 0;
@@ -418,6 +528,24 @@ var RRuleTemporal = class {
418
528
  }
419
529
  return results;
420
530
  }
531
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
532
+ const start = this.originalDtstart;
533
+ let yearCursor = start.with({ month: 1, day: 1 });
534
+ outer_year: while (true) {
535
+ const occs = this.generateYearlyOccurrences(yearCursor);
536
+ for (const occ of occs) {
537
+ const inst = occ.toInstant();
538
+ if (inc ? Temporal.Instant.compare(inst, endInst) > 0 : Temporal.Instant.compare(inst, endInst) >= 0) {
539
+ break outer_year;
540
+ }
541
+ if (Temporal.Instant.compare(inst, startInst) >= 0) {
542
+ results.push(occ);
543
+ }
544
+ }
545
+ yearCursor = yearCursor.add({ years: this.opts.interval });
546
+ }
547
+ return results;
548
+ }
421
549
  if (this.opts.freq === "WEEKLY") {
422
550
  const startInst2 = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
423
551
  const endInst2 = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
@@ -508,24 +636,123 @@ var RRuleTemporal = class {
508
636
  const iso = this.originalDtstart.toString({ smallestUnit: "second" }).replace(/[-:]/g, "");
509
637
  const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
510
638
  const parts = [];
511
- const { freq, interval, count, byHour, byMinute, byDay, byMonth } = this.opts;
639
+ const {
640
+ freq,
641
+ interval,
642
+ count,
643
+ until,
644
+ byHour,
645
+ byMinute,
646
+ byDay,
647
+ byMonth,
648
+ byMonthDay
649
+ } = this.opts;
512
650
  parts.push(`FREQ=${freq}`);
513
651
  if (interval !== 1) parts.push(`INTERVAL=${interval}`);
514
652
  if (count !== void 0) parts.push(`COUNT=${count}`);
653
+ if (until) {
654
+ const u = until.toInstant().toString().replace(/[-:]/g, "");
655
+ parts.push(`UNTIL=${u.slice(0, 15)}Z`);
656
+ }
515
657
  if (byHour) parts.push(`BYHOUR=${byHour.join(",")}`);
516
658
  if (byMinute) parts.push(`BYMINUTE=${byMinute.join(",")}`);
517
659
  if (byDay) parts.push(`BYDAY=${byDay.join(",")}`);
518
660
  if (byMonth) parts.push(`BYMONTH=${byMonth.join(",")}`);
661
+ if (byMonthDay) parts.push(`BYMONTHDAY=${byMonthDay.join(",")}`);
519
662
  return [dtLine, `RRULE:${parts.join(";")}`].join("\n");
520
663
  }
664
+ /**
665
+ * Convert this rule to a human readable English description.
666
+ */
667
+ toText(formatter = defaultDateFormatter) {
668
+ const {
669
+ freq,
670
+ interval = 1,
671
+ count,
672
+ until,
673
+ byDay,
674
+ byHour,
675
+ byMinute,
676
+ byMonth,
677
+ byMonthDay
678
+ } = this.opts;
679
+ const parts = ["every"];
680
+ const base = {
681
+ YEARLY: "year",
682
+ MONTHLY: "month",
683
+ WEEKLY: "week",
684
+ DAILY: "day",
685
+ HOURLY: "hour",
686
+ MINUTELY: "minute",
687
+ SECONDLY: "second"
688
+ }[freq];
689
+ const daysNormalized = byDay?.map((d) => d.toUpperCase());
690
+ const isWeekdays = daysNormalized && daysNormalized.length === 5 && ["MO", "TU", "WE", "TH", "FR"].every((d) => daysNormalized.includes(d));
691
+ const isEveryday = daysNormalized && daysNormalized.length === 7 && ["MO", "TU", "WE", "TH", "FR", "SA", "SU"].every(
692
+ (d) => daysNormalized.includes(d)
693
+ );
694
+ if (freq === "WEEKLY" && interval === 1 && isWeekdays) {
695
+ parts.push("weekday");
696
+ } else if (freq === "WEEKLY" && interval === 1 && isEveryday) {
697
+ parts.push("day");
698
+ } else {
699
+ if (interval !== 1) {
700
+ parts.push(interval.toString(), base + "s");
701
+ } else {
702
+ parts.push(base);
703
+ }
704
+ }
705
+ if (freq === "WEEKLY" && byDay && !isWeekdays && !isEveryday) {
706
+ parts.push("on", list(byDay, formatByDayToken));
707
+ } else if (byDay && freq !== "WEEKLY") {
708
+ parts.push("on", list(byDay, formatByDayToken));
709
+ }
710
+ if (byMonth) {
711
+ parts.push(
712
+ "in",
713
+ list(byMonth, (m) => MONTH_NAMES[m - 1])
714
+ );
715
+ }
716
+ if (byMonthDay) {
717
+ parts.push(
718
+ "on the",
719
+ list(byMonthDay, (d) => ordinal(d)),
720
+ "day of the month"
721
+ );
722
+ }
723
+ if (byHour) {
724
+ const minutes = byMinute ?? [0];
725
+ const times = byHour.flatMap((h) => minutes.map((m) => formatTime(h, m)));
726
+ parts.push("at", list(times));
727
+ parts.push(tzAbbreviation(this.originalDtstart));
728
+ }
729
+ if (until) {
730
+ parts.push(
731
+ "until",
732
+ formatter(until.year, MONTH_NAMES[until.month - 1], until.day)
733
+ );
734
+ } else if (count !== void 0) {
735
+ parts.push("for", count.toString(), count === 1 ? "time" : "times");
736
+ }
737
+ return parts.join(" ");
738
+ }
521
739
  /**
522
740
  * Given any date in a month, return all the ZonedDateTimes in that month
523
741
  * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
524
742
  */
525
743
  generateMonthlyOccurrences(sample) {
526
- const { byDay, byMonth, tzid } = this.opts;
744
+ const { byDay, byMonth, byMonthDay } = this.opts;
527
745
  if (byMonth && !byMonth.includes(sample.month)) return [];
528
- if (!byDay || byDay.length === 0) {
746
+ const lastDay = sample.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
747
+ let byMonthDayHits = [];
748
+ if (byMonthDay && byMonthDay.length > 0) {
749
+ byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
750
+ }
751
+ if (!byDay && byMonthDayHits.length) {
752
+ const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
753
+ return dates.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
754
+ }
755
+ if (!byDay) {
529
756
  return this.expandByHourMinute(sample);
530
757
  }
531
758
  const dayMap = {
@@ -549,20 +776,38 @@ var RRuleTemporal = class {
549
776
  (buckets[dow] ||= []).push(cursor.day);
550
777
  cursor = cursor.add({ days: 1 });
551
778
  }
552
- const hits = [];
779
+ const byDayHits = [];
553
780
  for (const { ord, wd } of tokens) {
554
- const list = buckets[wd] ?? [];
555
- if (!list.length) continue;
781
+ const list2 = buckets[wd] ?? [];
782
+ if (!list2.length) continue;
556
783
  if (ord === 0) {
557
- for (const d of list) hits.push(sample.with({ day: d }));
784
+ for (const d of list2) byDayHits.push(d);
558
785
  } else {
559
- const idx = ord > 0 ? ord - 1 : list.length + ord;
560
- const dayN = list[idx];
561
- if (dayN) hits.push(sample.with({ day: dayN }));
786
+ const idx = ord > 0 ? ord - 1 : list2.length + ord;
787
+ const dayN = list2[idx];
788
+ if (dayN) byDayHits.push(dayN);
562
789
  }
563
790
  }
791
+ let finalDays = byDayHits;
792
+ if (byMonthDayHits.length) {
793
+ finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
794
+ }
795
+ const hits = finalDays.map((d) => sample.with({ day: d }));
564
796
  return hits.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
565
797
  }
798
+ /**
799
+ * Given any date in a year, return all ZonedDateTimes in that year matching
800
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
801
+ * if BYMONTH is not specified.
802
+ */
803
+ generateYearlyOccurrences(sample) {
804
+ const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : [this.originalDtstart.month];
805
+ const occs = months.flatMap((m) => {
806
+ const monthSample = sample.with({ month: m, day: 1 });
807
+ return this.generateMonthlyOccurrences(monthSample);
808
+ });
809
+ return occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
810
+ }
566
811
  };
567
812
  export {
568
813
  RRuleTemporal
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rrule-temporal",
3
- "version": "0.1.7",
3
+ "version": "0.2.1",
4
4
  "description": "Recurrence rule processing using Temporal PlainDate/PlainDateTime",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -13,7 +13,8 @@
13
13
  },
14
14
  "scripts": {
15
15
  "build": "tsup",
16
- "test": "jest"
16
+ "test": "jest",
17
+ "prepare": "npm run build"
17
18
  },
18
19
  "repository": {
19
20
  "type": "git",