rrule-temporal 0.3.1 → 0.3.2

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/dist/index.cjs CHANGED
@@ -78,32 +78,79 @@ function formatByDayToken(tok) {
78
78
  if (ord === -1) return `last ${name}`;
79
79
  return `${ordinal(ord)} ${name}`;
80
80
  }
81
+ function unfoldLine(foldedLine) {
82
+ return foldedLine.replace(/\r?\n[ \t]/g, "");
83
+ }
84
+ function parseDateValues(dateValues, tzid) {
85
+ const dates = [];
86
+ for (const dateValue of dateValues) {
87
+ if (/Z$/.test(dateValue)) {
88
+ const iso = `${dateValue.slice(0, 4)}-${dateValue.slice(4, 6)}-${dateValue.slice(6, 8)}T${dateValue.slice(9, 15)}Z`;
89
+ dates.push(import_polyfill.Temporal.Instant.from(iso).toZonedDateTimeISO(
90
+ tzid || "UTC"
91
+ ));
92
+ } else {
93
+ const isoDate = `${dateValue.slice(0, 4)}-${dateValue.slice(4, 6)}-${dateValue.slice(6, 8)}T${dateValue.slice(9)}`;
94
+ dates.push(import_polyfill.Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid));
95
+ }
96
+ }
97
+ return dates;
98
+ }
81
99
  function parseRRuleString(input, fallbackDtstart) {
100
+ const unfoldedInput = unfoldLine(input);
82
101
  let dtstart;
83
102
  let tzid = "UTC";
84
103
  let rruleLine;
85
- if (/^DTSTART/m.test(input)) {
86
- const [dtLine, rrLine] = input.split(/\r?\n/);
87
- const m = dtLine?.match(/DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{6})/);
104
+ let exDate = [];
105
+ let rDate = [];
106
+ if (/^DTSTART/mi.test(unfoldedInput)) {
107
+ const lines = unfoldedInput.split(/\r?\n/);
108
+ const dtLine = lines[0];
109
+ const rrLine = lines.find((line) => line.match(/^RRULE:/i));
110
+ const exLines = lines.filter((line) => line.match(/^EXDATE/i));
111
+ const rLines = lines.filter((line) => line.match(/^RDATE/i));
112
+ const m = dtLine?.match(/DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{6})/i);
88
113
  if (!m) throw new Error("Invalid DTSTART in ICS snippet");
89
114
  tzid = m[1] || tzid;
90
115
  const isoDate = `${m[2].slice(0, 4)}-${m[2].slice(4, 6)}-${m[2].slice(6, 8)}T${m[2].slice(9)}`;
91
116
  dtstart = import_polyfill.Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid);
92
117
  rruleLine = rrLine;
118
+ for (const exLine of exLines) {
119
+ const exMatch = exLine.match(/EXDATE(?:;TZID=([^:]+))?:(.+)/i);
120
+ if (exMatch) {
121
+ const exTzid = exMatch[1] || tzid;
122
+ const dateValues = exMatch[2].split(",");
123
+ exDate.push(...parseDateValues(dateValues, exTzid));
124
+ }
125
+ }
126
+ for (const rLine of rLines) {
127
+ const rMatch = rLine.match(/RDATE(?:;TZID=([^:]+))?:(.+)/i);
128
+ if (rMatch) {
129
+ const rTzid = rMatch[1] || tzid;
130
+ const dateValues = rMatch[2].split(",");
131
+ rDate.push(...parseDateValues(dateValues, rTzid));
132
+ }
133
+ }
93
134
  } else {
94
135
  if (!fallbackDtstart)
95
136
  throw new Error("dtstart required when parsing RRULE alone");
96
137
  dtstart = fallbackDtstart;
97
138
  tzid = fallbackDtstart.timeZoneId;
98
- rruleLine = input.replace(/^RRULE:/, "RRULE:");
139
+ rruleLine = unfoldedInput.replace(/^RRULE:/i, "RRULE:");
99
140
  }
100
- const parts = rruleLine.replace(/^RRULE:/, "").split(";");
101
- const opts = { dtstart, tzid };
141
+ const parts = rruleLine ? rruleLine.replace(/^RRULE:/i, "").split(";") : [];
142
+ const opts = {
143
+ dtstart,
144
+ tzid,
145
+ exDate: exDate.length > 0 ? exDate : void 0,
146
+ rDate: rDate.length > 0 ? rDate : void 0
147
+ };
102
148
  for (const part of parts) {
103
149
  const [key, val] = part.split("=");
104
- switch (key) {
150
+ if (!key) continue;
151
+ switch (key.toUpperCase()) {
105
152
  case "FREQ":
106
- opts.freq = val;
153
+ opts.freq = val.toUpperCase();
107
154
  break;
108
155
  case "INTERVAL":
109
156
  opts.interval = parseInt(val, 10);
@@ -180,6 +227,7 @@ var RRuleTemporal = class {
180
227
  tzid;
181
228
  originalDtstart;
182
229
  opts;
230
+ maxIterations;
183
231
  constructor(params) {
184
232
  let manual;
185
233
  if ("rruleString" in params) {
@@ -204,6 +252,7 @@ var RRuleTemporal = class {
204
252
  throw new Error("Manual until must be a ZonedDateTime");
205
253
  }
206
254
  this.opts = this.sanitizeOpts(manual);
255
+ this.maxIterations = manual.maxIterations ?? 1e4;
207
256
  }
208
257
  sanitizeOpts(opts) {
209
258
  const validDay = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/;
@@ -492,11 +541,15 @@ var RRuleTemporal = class {
492
541
  throw new Error("all() requires iterator when no COUNT/UNTIL");
493
542
  }
494
543
  const dates = [];
544
+ let iterationCount = 0;
495
545
  if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
496
546
  const start = this.originalDtstart;
497
547
  let monthCursor = start.with({ day: 1 });
498
548
  let matchCount2 = 0;
499
549
  outer_month: while (true) {
550
+ if (++iterationCount > this.maxIterations) {
551
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
552
+ }
500
553
  const occs = this.generateMonthlyOccurrences(monthCursor);
501
554
  if (monthCursor.month === start.month && occs.some((o) => import_polyfill.Temporal.ZonedDateTime.compare(o, start) < 0)) {
502
555
  monthCursor = monthCursor.add({ months: this.opts.interval });
@@ -545,6 +598,9 @@ var RRuleTemporal = class {
545
598
  let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
546
599
  let matchCount2 = 0;
547
600
  outer_week: while (true) {
601
+ if (++iterationCount > this.maxIterations) {
602
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
603
+ }
548
604
  const occs = dows.flatMap((dw) => {
549
605
  const delta = (dw - wkstDay + 7) % 7;
550
606
  const sameDate = weekCursor.add({ days: delta });
@@ -574,6 +630,9 @@ var RRuleTemporal = class {
574
630
  let yearOffset = 0;
575
631
  let matchCount2 = 0;
576
632
  while (true) {
633
+ if (++iterationCount > this.maxIterations) {
634
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
635
+ }
577
636
  const year = start.year + yearOffset * this.opts.interval;
578
637
  for (const month of months) {
579
638
  let occ = start.with({ year, month });
@@ -602,6 +661,9 @@ var RRuleTemporal = class {
602
661
  let yearCursor = start.with({ month: 1, day: 1 });
603
662
  let matchCount2 = 0;
604
663
  outer_year: while (true) {
664
+ if (++iterationCount > this.maxIterations) {
665
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
666
+ }
605
667
  const occs = this.generateYearlyOccurrences(yearCursor);
606
668
  for (const occ of occs) {
607
669
  if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
@@ -626,6 +688,9 @@ var RRuleTemporal = class {
626
688
  let yearCursor = start.with({ month: 1, day: 1 });
627
689
  let matchCount2 = 0;
628
690
  outer_year2: while (true) {
691
+ if (++iterationCount > this.maxIterations) {
692
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
693
+ }
629
694
  const occs = this.generateYearlyOccurrences(yearCursor);
630
695
  for (const occ of occs) {
631
696
  if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
@@ -648,6 +713,9 @@ var RRuleTemporal = class {
648
713
  let current = this.computeFirst();
649
714
  let matchCount = 0;
650
715
  while (true) {
716
+ if (++iterationCount > this.maxIterations) {
717
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
718
+ }
651
719
  if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
652
720
  break;
653
721
  }
@@ -672,10 +740,7 @@ var RRuleTemporal = class {
672
740
  */
673
741
  mergeAndDeduplicateRDates(dates) {
674
742
  if (!this.opts.rDate) return dates;
675
- const extras = this.opts.rDate.map(
676
- (d) => d instanceof import_polyfill.Temporal.ZonedDateTime ? d : import_polyfill.Temporal.Instant.from(d.toISOString()).toZonedDateTimeISO(this.tzid)
677
- );
678
- dates.push(...extras);
743
+ dates.push(...this.opts.rDate);
679
744
  dates.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
680
745
  const dedup = [];
681
746
  for (const d of dates) {
@@ -685,6 +750,19 @@ var RRuleTemporal = class {
685
750
  }
686
751
  return dedup;
687
752
  }
753
+ /**
754
+ * Excludes exDate entries from the given array of dates.
755
+ * @param dates - Array of dates to filter
756
+ * @returns Filtered array with exDate entries removed
757
+ */
758
+ excludeExDates(dates) {
759
+ if (!this.opts.exDate || this.opts.exDate.length === 0) return dates;
760
+ return dates.filter((date) => {
761
+ return !this.opts.exDate.some(
762
+ (exDate) => import_polyfill.Temporal.ZonedDateTime.compare(date, exDate) === 0
763
+ );
764
+ });
765
+ }
688
766
  /**
689
767
  * Applies count limit and merges rDates with the rule-generated dates.
690
768
  * @param dates - Array of dates generated by the rule
@@ -693,10 +771,11 @@ var RRuleTemporal = class {
693
771
  */
694
772
  applyCountLimitAndMergeRDates(dates, iterator) {
695
773
  const merged = this.mergeAndDeduplicateRDates(dates);
774
+ const excluded = this.excludeExDates(merged);
696
775
  if (this.opts.count !== void 0) {
697
776
  let finalCount = 0;
698
777
  const finalDates = [];
699
- for (const d of merged) {
778
+ for (const d of excluded) {
700
779
  if (finalCount >= this.opts.count) break;
701
780
  if (iterator && !iterator(d, finalCount)) break;
702
781
  finalDates.push(d);
@@ -704,7 +783,7 @@ var RRuleTemporal = class {
704
783
  }
705
784
  return finalDates;
706
785
  }
707
- return merged;
786
+ return excluded;
708
787
  }
709
788
  /**
710
789
  * Checks if the count limit should break the loop based on rDate presence.
@@ -716,7 +795,10 @@ var RRuleTemporal = class {
716
795
  if (!this.opts.rDate) {
717
796
  return matchCount >= this.opts.count;
718
797
  }
719
- return matchCount >= this.opts.count * 2;
798
+ const rDateCount = this.opts.rDate.length;
799
+ const targetRuleCount = Math.max(this.opts.count - rDateCount, 0);
800
+ const safetyMargin = Math.min(targetRuleCount, 10);
801
+ return matchCount >= targetRuleCount + safetyMargin;
720
802
  }
721
803
  /**
722
804
  * Returns all occurrences of the rule within a specified time window.
@@ -729,9 +811,13 @@ var RRuleTemporal = class {
729
811
  const startInst = after instanceof Date ? import_polyfill.Temporal.Instant.from(after.toISOString()) : after.toInstant();
730
812
  const endInst = before instanceof Date ? import_polyfill.Temporal.Instant.from(before.toISOString()) : before.toInstant();
731
813
  const results = [];
814
+ let iterationCount = 0;
732
815
  if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
733
816
  let monthCursor = this.computeFirst().with({ day: 1 });
734
817
  outer: while (true) {
818
+ if (++iterationCount > this.maxIterations) {
819
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
820
+ }
735
821
  const occs = this.generateMonthlyOccurrences(monthCursor);
736
822
  for (const occ of occs) {
737
823
  const inst = occ.toInstant();
@@ -752,6 +838,9 @@ var RRuleTemporal = class {
752
838
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
753
839
  let yearOffset = 0;
754
840
  outer: while (true) {
841
+ if (++iterationCount > this.maxIterations) {
842
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
843
+ }
755
844
  const year = start.year + yearOffset * this.opts.interval;
756
845
  for (const month of months) {
757
846
  let occ = start.with({ year, month });
@@ -773,6 +862,9 @@ var RRuleTemporal = class {
773
862
  const start = this.originalDtstart;
774
863
  let yearCursor = start.with({ month: 1, day: 1 });
775
864
  outer_year: while (true) {
865
+ if (++iterationCount > this.maxIterations) {
866
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
867
+ }
776
868
  const occs = this.generateYearlyOccurrences(yearCursor);
777
869
  for (const occ of occs) {
778
870
  const inst = occ.toInstant();
@@ -792,6 +884,9 @@ var RRuleTemporal = class {
792
884
  const start = this.originalDtstart;
793
885
  let yearCursor = start.with({ month: 1, day: 1 });
794
886
  outer_year2: while (true) {
887
+ if (++iterationCount > this.maxIterations) {
888
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
889
+ }
795
890
  const occs = this.generateYearlyOccurrences(yearCursor);
796
891
  for (const occ of occs) {
797
892
  const inst = occ.toInstant();
@@ -813,6 +908,9 @@ var RRuleTemporal = class {
813
908
  let weekCursor = this.computeFirst();
814
909
  const results2 = [];
815
910
  outer: while (true) {
911
+ if (++iterationCount > this.maxIterations) {
912
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
913
+ }
816
914
  const occs = this.generateWeeklyOccurrences(weekCursor);
817
915
  for (const occ of occs) {
818
916
  const inst = occ.toInstant();
@@ -830,6 +928,9 @@ var RRuleTemporal = class {
830
928
  }
831
929
  let current = this.computeFirst();
832
930
  while (true) {
931
+ if (++iterationCount > this.maxIterations) {
932
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
933
+ }
833
934
  const inst = current.toInstant();
834
935
  if (inc) {
835
936
  if (import_polyfill.Temporal.Instant.compare(inst, endInst) > 0) break;
@@ -998,7 +1099,10 @@ var RRuleTemporal = class {
998
1099
  if (byMonthDay && byMonthDay.length > 0) {
999
1100
  byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
1000
1101
  }
1001
- if (!byDay && byMonthDayHits.length) {
1102
+ if (!byDay && byMonthDay && byMonthDay.length > 0) {
1103
+ if (byMonthDayHits.length === 0) {
1104
+ return [];
1105
+ }
1002
1106
  const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
1003
1107
  return dates.flatMap((z) => this.expandByTime(z)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1004
1108
  }
@@ -1039,7 +1143,10 @@ var RRuleTemporal = class {
1039
1143
  }
1040
1144
  }
1041
1145
  let finalDays = byDayHits;
1042
- if (byMonthDayHits.length) {
1146
+ if (byMonthDay && byMonthDay.length > 0) {
1147
+ if (byMonthDayHits.length === 0) {
1148
+ return [];
1149
+ }
1043
1150
  finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
1044
1151
  }
1045
1152
  const hits = finalDays.map((d) => sample.with({ day: d }));
@@ -1147,11 +1254,8 @@ var RRuleTemporal = class {
1147
1254
  return out.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1148
1255
  }
1149
1256
  mergeRDates(list2, startInst, endInst, inc) {
1150
- if (!this.opts.rDate) return list2;
1151
- const extras = this.opts.rDate.map(
1152
- (d) => d instanceof import_polyfill.Temporal.ZonedDateTime ? d : import_polyfill.Temporal.Instant.from(d.toISOString()).toZonedDateTimeISO(this.tzid)
1153
- );
1154
- for (const z of extras) {
1257
+ if (!this.opts.rDate) return this.excludeExDates(list2);
1258
+ for (const z of this.opts.rDate) {
1155
1259
  const inst = z.toInstant();
1156
1260
  const startOk = inc ? import_polyfill.Temporal.Instant.compare(inst, startInst) >= 0 : import_polyfill.Temporal.Instant.compare(inst, startInst) > 0;
1157
1261
  const endOk = inc ? import_polyfill.Temporal.Instant.compare(inst, endInst) <= 0 : import_polyfill.Temporal.Instant.compare(inst, endInst) < 0;
@@ -1164,7 +1268,7 @@ var RRuleTemporal = class {
1164
1268
  dedup.push(d);
1165
1269
  }
1166
1270
  }
1167
- return dedup;
1271
+ return this.excludeExDates(dedup);
1168
1272
  }
1169
1273
  };
1170
1274
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.d.cts CHANGED
@@ -4,6 +4,7 @@ type DateFormatter = (year: number, month: string, day: number) => string;
4
4
  type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
5
5
  interface BaseOpts {
6
6
  tzid?: string;
7
+ maxIterations?: number;
7
8
  }
8
9
  interface ManualOpts extends BaseOpts {
9
10
  freq: Freq;
@@ -20,7 +21,8 @@ interface ManualOpts extends BaseOpts {
20
21
  byWeekNo?: number[];
21
22
  bySetPos?: number[];
22
23
  wkst?: string;
23
- rDate?: (Date | Temporal.ZonedDateTime)[];
24
+ rDate?: Temporal.ZonedDateTime[];
25
+ exDate?: Temporal.ZonedDateTime[];
24
26
  dtstart: Temporal.ZonedDateTime;
25
27
  }
26
28
  interface IcsOpts extends BaseOpts {
@@ -31,6 +33,7 @@ declare class RRuleTemporal {
31
33
  private tzid;
32
34
  private originalDtstart;
33
35
  private opts;
36
+ private maxIterations;
34
37
  constructor(params: {
35
38
  rruleString: string;
36
39
  } | ManualOpts);
@@ -64,6 +67,12 @@ declare class RRuleTemporal {
64
67
  * @returns Merged and deduplicated array of dates
65
68
  */
66
69
  private mergeAndDeduplicateRDates;
70
+ /**
71
+ * Excludes exDate entries from the given array of dates.
72
+ * @param dates - Array of dates to filter
73
+ * @returns Filtered array with exDate entries removed
74
+ */
75
+ private excludeExDates;
67
76
  /**
68
77
  * Applies count limit and merges rDates with the rule-generated dates.
69
78
  * @param dates - Array of dates generated by the rule
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ type DateFormatter = (year: number, month: string, day: number) => string;
4
4
  type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
5
5
  interface BaseOpts {
6
6
  tzid?: string;
7
+ maxIterations?: number;
7
8
  }
8
9
  interface ManualOpts extends BaseOpts {
9
10
  freq: Freq;
@@ -20,7 +21,8 @@ interface ManualOpts extends BaseOpts {
20
21
  byWeekNo?: number[];
21
22
  bySetPos?: number[];
22
23
  wkst?: string;
23
- rDate?: (Date | Temporal.ZonedDateTime)[];
24
+ rDate?: Temporal.ZonedDateTime[];
25
+ exDate?: Temporal.ZonedDateTime[];
24
26
  dtstart: Temporal.ZonedDateTime;
25
27
  }
26
28
  interface IcsOpts extends BaseOpts {
@@ -31,6 +33,7 @@ declare class RRuleTemporal {
31
33
  private tzid;
32
34
  private originalDtstart;
33
35
  private opts;
36
+ private maxIterations;
34
37
  constructor(params: {
35
38
  rruleString: string;
36
39
  } | ManualOpts);
@@ -64,6 +67,12 @@ declare class RRuleTemporal {
64
67
  * @returns Merged and deduplicated array of dates
65
68
  */
66
69
  private mergeAndDeduplicateRDates;
70
+ /**
71
+ * Excludes exDate entries from the given array of dates.
72
+ * @param dates - Array of dates to filter
73
+ * @returns Filtered array with exDate entries removed
74
+ */
75
+ private excludeExDates;
67
76
  /**
68
77
  * Applies count limit and merges rDates with the rule-generated dates.
69
78
  * @param dates - Array of dates generated by the rule
package/dist/index.js CHANGED
@@ -54,32 +54,79 @@ function formatByDayToken(tok) {
54
54
  if (ord === -1) return `last ${name}`;
55
55
  return `${ordinal(ord)} ${name}`;
56
56
  }
57
+ function unfoldLine(foldedLine) {
58
+ return foldedLine.replace(/\r?\n[ \t]/g, "");
59
+ }
60
+ function parseDateValues(dateValues, tzid) {
61
+ const dates = [];
62
+ for (const dateValue of dateValues) {
63
+ if (/Z$/.test(dateValue)) {
64
+ const iso = `${dateValue.slice(0, 4)}-${dateValue.slice(4, 6)}-${dateValue.slice(6, 8)}T${dateValue.slice(9, 15)}Z`;
65
+ dates.push(Temporal.Instant.from(iso).toZonedDateTimeISO(
66
+ tzid || "UTC"
67
+ ));
68
+ } else {
69
+ const isoDate = `${dateValue.slice(0, 4)}-${dateValue.slice(4, 6)}-${dateValue.slice(6, 8)}T${dateValue.slice(9)}`;
70
+ dates.push(Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid));
71
+ }
72
+ }
73
+ return dates;
74
+ }
57
75
  function parseRRuleString(input, fallbackDtstart) {
76
+ const unfoldedInput = unfoldLine(input);
58
77
  let dtstart;
59
78
  let tzid = "UTC";
60
79
  let rruleLine;
61
- if (/^DTSTART/m.test(input)) {
62
- const [dtLine, rrLine] = input.split(/\r?\n/);
63
- const m = dtLine?.match(/DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{6})/);
80
+ let exDate = [];
81
+ let rDate = [];
82
+ if (/^DTSTART/mi.test(unfoldedInput)) {
83
+ const lines = unfoldedInput.split(/\r?\n/);
84
+ const dtLine = lines[0];
85
+ const rrLine = lines.find((line) => line.match(/^RRULE:/i));
86
+ const exLines = lines.filter((line) => line.match(/^EXDATE/i));
87
+ const rLines = lines.filter((line) => line.match(/^RDATE/i));
88
+ const m = dtLine?.match(/DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{6})/i);
64
89
  if (!m) throw new Error("Invalid DTSTART in ICS snippet");
65
90
  tzid = m[1] || tzid;
66
91
  const isoDate = `${m[2].slice(0, 4)}-${m[2].slice(4, 6)}-${m[2].slice(6, 8)}T${m[2].slice(9)}`;
67
92
  dtstart = Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid);
68
93
  rruleLine = rrLine;
94
+ for (const exLine of exLines) {
95
+ const exMatch = exLine.match(/EXDATE(?:;TZID=([^:]+))?:(.+)/i);
96
+ if (exMatch) {
97
+ const exTzid = exMatch[1] || tzid;
98
+ const dateValues = exMatch[2].split(",");
99
+ exDate.push(...parseDateValues(dateValues, exTzid));
100
+ }
101
+ }
102
+ for (const rLine of rLines) {
103
+ const rMatch = rLine.match(/RDATE(?:;TZID=([^:]+))?:(.+)/i);
104
+ if (rMatch) {
105
+ const rTzid = rMatch[1] || tzid;
106
+ const dateValues = rMatch[2].split(",");
107
+ rDate.push(...parseDateValues(dateValues, rTzid));
108
+ }
109
+ }
69
110
  } else {
70
111
  if (!fallbackDtstart)
71
112
  throw new Error("dtstart required when parsing RRULE alone");
72
113
  dtstart = fallbackDtstart;
73
114
  tzid = fallbackDtstart.timeZoneId;
74
- rruleLine = input.replace(/^RRULE:/, "RRULE:");
115
+ rruleLine = unfoldedInput.replace(/^RRULE:/i, "RRULE:");
75
116
  }
76
- const parts = rruleLine.replace(/^RRULE:/, "").split(";");
77
- const opts = { dtstart, tzid };
117
+ const parts = rruleLine ? rruleLine.replace(/^RRULE:/i, "").split(";") : [];
118
+ const opts = {
119
+ dtstart,
120
+ tzid,
121
+ exDate: exDate.length > 0 ? exDate : void 0,
122
+ rDate: rDate.length > 0 ? rDate : void 0
123
+ };
78
124
  for (const part of parts) {
79
125
  const [key, val] = part.split("=");
80
- switch (key) {
126
+ if (!key) continue;
127
+ switch (key.toUpperCase()) {
81
128
  case "FREQ":
82
- opts.freq = val;
129
+ opts.freq = val.toUpperCase();
83
130
  break;
84
131
  case "INTERVAL":
85
132
  opts.interval = parseInt(val, 10);
@@ -156,6 +203,7 @@ var RRuleTemporal = class {
156
203
  tzid;
157
204
  originalDtstart;
158
205
  opts;
206
+ maxIterations;
159
207
  constructor(params) {
160
208
  let manual;
161
209
  if ("rruleString" in params) {
@@ -180,6 +228,7 @@ var RRuleTemporal = class {
180
228
  throw new Error("Manual until must be a ZonedDateTime");
181
229
  }
182
230
  this.opts = this.sanitizeOpts(manual);
231
+ this.maxIterations = manual.maxIterations ?? 1e4;
183
232
  }
184
233
  sanitizeOpts(opts) {
185
234
  const validDay = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/;
@@ -468,11 +517,15 @@ var RRuleTemporal = class {
468
517
  throw new Error("all() requires iterator when no COUNT/UNTIL");
469
518
  }
470
519
  const dates = [];
520
+ let iterationCount = 0;
471
521
  if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
472
522
  const start = this.originalDtstart;
473
523
  let monthCursor = start.with({ day: 1 });
474
524
  let matchCount2 = 0;
475
525
  outer_month: while (true) {
526
+ if (++iterationCount > this.maxIterations) {
527
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
528
+ }
476
529
  const occs = this.generateMonthlyOccurrences(monthCursor);
477
530
  if (monthCursor.month === start.month && occs.some((o) => Temporal.ZonedDateTime.compare(o, start) < 0)) {
478
531
  monthCursor = monthCursor.add({ months: this.opts.interval });
@@ -521,6 +574,9 @@ var RRuleTemporal = class {
521
574
  let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
522
575
  let matchCount2 = 0;
523
576
  outer_week: while (true) {
577
+ if (++iterationCount > this.maxIterations) {
578
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
579
+ }
524
580
  const occs = dows.flatMap((dw) => {
525
581
  const delta = (dw - wkstDay + 7) % 7;
526
582
  const sameDate = weekCursor.add({ days: delta });
@@ -550,6 +606,9 @@ var RRuleTemporal = class {
550
606
  let yearOffset = 0;
551
607
  let matchCount2 = 0;
552
608
  while (true) {
609
+ if (++iterationCount > this.maxIterations) {
610
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
611
+ }
553
612
  const year = start.year + yearOffset * this.opts.interval;
554
613
  for (const month of months) {
555
614
  let occ = start.with({ year, month });
@@ -578,6 +637,9 @@ var RRuleTemporal = class {
578
637
  let yearCursor = start.with({ month: 1, day: 1 });
579
638
  let matchCount2 = 0;
580
639
  outer_year: while (true) {
640
+ if (++iterationCount > this.maxIterations) {
641
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
642
+ }
581
643
  const occs = this.generateYearlyOccurrences(yearCursor);
582
644
  for (const occ of occs) {
583
645
  if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
@@ -602,6 +664,9 @@ var RRuleTemporal = class {
602
664
  let yearCursor = start.with({ month: 1, day: 1 });
603
665
  let matchCount2 = 0;
604
666
  outer_year2: while (true) {
667
+ if (++iterationCount > this.maxIterations) {
668
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
669
+ }
605
670
  const occs = this.generateYearlyOccurrences(yearCursor);
606
671
  for (const occ of occs) {
607
672
  if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
@@ -624,6 +689,9 @@ var RRuleTemporal = class {
624
689
  let current = this.computeFirst();
625
690
  let matchCount = 0;
626
691
  while (true) {
692
+ if (++iterationCount > this.maxIterations) {
693
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
694
+ }
627
695
  if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
628
696
  break;
629
697
  }
@@ -648,10 +716,7 @@ var RRuleTemporal = class {
648
716
  */
649
717
  mergeAndDeduplicateRDates(dates) {
650
718
  if (!this.opts.rDate) return dates;
651
- const extras = this.opts.rDate.map(
652
- (d) => d instanceof Temporal.ZonedDateTime ? d : Temporal.Instant.from(d.toISOString()).toZonedDateTimeISO(this.tzid)
653
- );
654
- dates.push(...extras);
719
+ dates.push(...this.opts.rDate);
655
720
  dates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
656
721
  const dedup = [];
657
722
  for (const d of dates) {
@@ -661,6 +726,19 @@ var RRuleTemporal = class {
661
726
  }
662
727
  return dedup;
663
728
  }
729
+ /**
730
+ * Excludes exDate entries from the given array of dates.
731
+ * @param dates - Array of dates to filter
732
+ * @returns Filtered array with exDate entries removed
733
+ */
734
+ excludeExDates(dates) {
735
+ if (!this.opts.exDate || this.opts.exDate.length === 0) return dates;
736
+ return dates.filter((date) => {
737
+ return !this.opts.exDate.some(
738
+ (exDate) => Temporal.ZonedDateTime.compare(date, exDate) === 0
739
+ );
740
+ });
741
+ }
664
742
  /**
665
743
  * Applies count limit and merges rDates with the rule-generated dates.
666
744
  * @param dates - Array of dates generated by the rule
@@ -669,10 +747,11 @@ var RRuleTemporal = class {
669
747
  */
670
748
  applyCountLimitAndMergeRDates(dates, iterator) {
671
749
  const merged = this.mergeAndDeduplicateRDates(dates);
750
+ const excluded = this.excludeExDates(merged);
672
751
  if (this.opts.count !== void 0) {
673
752
  let finalCount = 0;
674
753
  const finalDates = [];
675
- for (const d of merged) {
754
+ for (const d of excluded) {
676
755
  if (finalCount >= this.opts.count) break;
677
756
  if (iterator && !iterator(d, finalCount)) break;
678
757
  finalDates.push(d);
@@ -680,7 +759,7 @@ var RRuleTemporal = class {
680
759
  }
681
760
  return finalDates;
682
761
  }
683
- return merged;
762
+ return excluded;
684
763
  }
685
764
  /**
686
765
  * Checks if the count limit should break the loop based on rDate presence.
@@ -692,7 +771,10 @@ var RRuleTemporal = class {
692
771
  if (!this.opts.rDate) {
693
772
  return matchCount >= this.opts.count;
694
773
  }
695
- return matchCount >= this.opts.count * 2;
774
+ const rDateCount = this.opts.rDate.length;
775
+ const targetRuleCount = Math.max(this.opts.count - rDateCount, 0);
776
+ const safetyMargin = Math.min(targetRuleCount, 10);
777
+ return matchCount >= targetRuleCount + safetyMargin;
696
778
  }
697
779
  /**
698
780
  * Returns all occurrences of the rule within a specified time window.
@@ -705,9 +787,13 @@ var RRuleTemporal = class {
705
787
  const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
706
788
  const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
707
789
  const results = [];
790
+ let iterationCount = 0;
708
791
  if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
709
792
  let monthCursor = this.computeFirst().with({ day: 1 });
710
793
  outer: while (true) {
794
+ if (++iterationCount > this.maxIterations) {
795
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
796
+ }
711
797
  const occs = this.generateMonthlyOccurrences(monthCursor);
712
798
  for (const occ of occs) {
713
799
  const inst = occ.toInstant();
@@ -728,6 +814,9 @@ var RRuleTemporal = class {
728
814
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
729
815
  let yearOffset = 0;
730
816
  outer: while (true) {
817
+ if (++iterationCount > this.maxIterations) {
818
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
819
+ }
731
820
  const year = start.year + yearOffset * this.opts.interval;
732
821
  for (const month of months) {
733
822
  let occ = start.with({ year, month });
@@ -749,6 +838,9 @@ var RRuleTemporal = class {
749
838
  const start = this.originalDtstart;
750
839
  let yearCursor = start.with({ month: 1, day: 1 });
751
840
  outer_year: while (true) {
841
+ if (++iterationCount > this.maxIterations) {
842
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
843
+ }
752
844
  const occs = this.generateYearlyOccurrences(yearCursor);
753
845
  for (const occ of occs) {
754
846
  const inst = occ.toInstant();
@@ -768,6 +860,9 @@ var RRuleTemporal = class {
768
860
  const start = this.originalDtstart;
769
861
  let yearCursor = start.with({ month: 1, day: 1 });
770
862
  outer_year2: while (true) {
863
+ if (++iterationCount > this.maxIterations) {
864
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
865
+ }
771
866
  const occs = this.generateYearlyOccurrences(yearCursor);
772
867
  for (const occ of occs) {
773
868
  const inst = occ.toInstant();
@@ -789,6 +884,9 @@ var RRuleTemporal = class {
789
884
  let weekCursor = this.computeFirst();
790
885
  const results2 = [];
791
886
  outer: while (true) {
887
+ if (++iterationCount > this.maxIterations) {
888
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
889
+ }
792
890
  const occs = this.generateWeeklyOccurrences(weekCursor);
793
891
  for (const occ of occs) {
794
892
  const inst = occ.toInstant();
@@ -806,6 +904,9 @@ var RRuleTemporal = class {
806
904
  }
807
905
  let current = this.computeFirst();
808
906
  while (true) {
907
+ if (++iterationCount > this.maxIterations) {
908
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
909
+ }
809
910
  const inst = current.toInstant();
810
911
  if (inc) {
811
912
  if (Temporal.Instant.compare(inst, endInst) > 0) break;
@@ -974,7 +1075,10 @@ var RRuleTemporal = class {
974
1075
  if (byMonthDay && byMonthDay.length > 0) {
975
1076
  byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
976
1077
  }
977
- if (!byDay && byMonthDayHits.length) {
1078
+ if (!byDay && byMonthDay && byMonthDay.length > 0) {
1079
+ if (byMonthDayHits.length === 0) {
1080
+ return [];
1081
+ }
978
1082
  const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
979
1083
  return dates.flatMap((z) => this.expandByTime(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
980
1084
  }
@@ -1015,7 +1119,10 @@ var RRuleTemporal = class {
1015
1119
  }
1016
1120
  }
1017
1121
  let finalDays = byDayHits;
1018
- if (byMonthDayHits.length) {
1122
+ if (byMonthDay && byMonthDay.length > 0) {
1123
+ if (byMonthDayHits.length === 0) {
1124
+ return [];
1125
+ }
1019
1126
  finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
1020
1127
  }
1021
1128
  const hits = finalDays.map((d) => sample.with({ day: d }));
@@ -1123,11 +1230,8 @@ var RRuleTemporal = class {
1123
1230
  return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1124
1231
  }
1125
1232
  mergeRDates(list2, startInst, endInst, inc) {
1126
- if (!this.opts.rDate) return list2;
1127
- const extras = this.opts.rDate.map(
1128
- (d) => d instanceof Temporal.ZonedDateTime ? d : Temporal.Instant.from(d.toISOString()).toZonedDateTimeISO(this.tzid)
1129
- );
1130
- for (const z of extras) {
1233
+ if (!this.opts.rDate) return this.excludeExDates(list2);
1234
+ for (const z of this.opts.rDate) {
1131
1235
  const inst = z.toInstant();
1132
1236
  const startOk = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
1133
1237
  const endOk = inc ? Temporal.Instant.compare(inst, endInst) <= 0 : Temporal.Instant.compare(inst, endInst) < 0;
@@ -1140,7 +1244,7 @@ var RRuleTemporal = class {
1140
1244
  dedup.push(d);
1141
1245
  }
1142
1246
  }
1143
- return dedup;
1247
+ return this.excludeExDates(dedup);
1144
1248
  }
1145
1249
  };
1146
1250
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rrule-temporal",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Recurrence rule processing using Temporal PlainDate/PlainDateTime",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",