rrule-temporal 0.2.7 → 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.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);
@@ -116,6 +163,21 @@ function parseRRuleString(input, fallbackDtstart) {
116
163
  case "BYMONTHDAY":
117
164
  opts.byMonthDay = val.split(",").map((n) => parseInt(n, 10));
118
165
  break;
166
+ case "BYSECOND":
167
+ opts.bySecond = val.split(",").map((n) => parseInt(n, 10)).sort((a, b) => a - b);
168
+ break;
169
+ case "BYYEARDAY":
170
+ opts.byYearDay = val.split(",").map((n) => parseInt(n, 10));
171
+ break;
172
+ case "BYWEEKNO":
173
+ opts.byWeekNo = val.split(",").map((n) => parseInt(n, 10));
174
+ break;
175
+ case "BYSETPOS":
176
+ opts.bySetPos = val.split(",").map((n) => parseInt(n, 10));
177
+ break;
178
+ case "WKST":
179
+ opts.wkst = val;
180
+ break;
119
181
  }
120
182
  }
121
183
  return opts;
@@ -141,6 +203,7 @@ var RRuleTemporal = class {
141
203
  tzid;
142
204
  originalDtstart;
143
205
  opts;
206
+ maxIterations;
144
207
  constructor(params) {
145
208
  let manual;
146
209
  if ("rruleString" in params) {
@@ -158,7 +221,54 @@ var RRuleTemporal = class {
158
221
  }
159
222
  if (!manual.freq) throw new Error("RRULE must include FREQ");
160
223
  manual.interval = manual.interval ?? 1;
161
- this.opts = manual;
224
+ if (manual.interval <= 0) {
225
+ throw new Error("Cannot create RRule: interval must be greater than 0");
226
+ }
227
+ if (manual.until && !(manual.until instanceof Temporal.ZonedDateTime)) {
228
+ throw new Error("Manual until must be a ZonedDateTime");
229
+ }
230
+ this.opts = this.sanitizeOpts(manual);
231
+ this.maxIterations = manual.maxIterations ?? 1e4;
232
+ }
233
+ sanitizeOpts(opts) {
234
+ const validDay = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/;
235
+ if (opts.byDay) {
236
+ opts.byDay = opts.byDay.filter((d) => validDay.test(d));
237
+ if (opts.byDay.length === 0) delete opts.byDay;
238
+ }
239
+ if (opts.byMonth) {
240
+ opts.byMonth = opts.byMonth.filter((n) => Number.isInteger(n) && n >= 1 && n <= 12);
241
+ if (opts.byMonth.length === 0) delete opts.byMonth;
242
+ }
243
+ if (opts.byMonthDay) {
244
+ opts.byMonthDay = opts.byMonthDay.filter((n) => Number.isInteger(n) && n !== 0 && n >= -31 && n <= 31);
245
+ if (opts.byMonthDay.length === 0) delete opts.byMonthDay;
246
+ }
247
+ if (opts.byYearDay) {
248
+ opts.byYearDay = opts.byYearDay.filter((n) => Number.isInteger(n) && n !== 0 && n >= -366 && n <= 366);
249
+ if (opts.byYearDay.length === 0) delete opts.byYearDay;
250
+ }
251
+ if (opts.byWeekNo) {
252
+ opts.byWeekNo = opts.byWeekNo.filter((n) => Number.isInteger(n) && n !== 0 && n >= -53 && n <= 53);
253
+ if (opts.byWeekNo.length === 0) delete opts.byWeekNo;
254
+ }
255
+ if (opts.byHour) {
256
+ opts.byHour = opts.byHour.filter((n) => Number.isInteger(n) && n >= 0 && n <= 23).sort((a, b) => a - b);
257
+ if (opts.byHour.length === 0) delete opts.byHour;
258
+ }
259
+ if (opts.byMinute) {
260
+ opts.byMinute = opts.byMinute.filter((n) => Number.isInteger(n) && n >= 0 && n <= 59).sort((a, b) => a - b);
261
+ if (opts.byMinute.length === 0) delete opts.byMinute;
262
+ }
263
+ if (opts.bySecond) {
264
+ opts.bySecond = opts.bySecond.filter((n) => Number.isInteger(n) && n >= 0 && n <= 59).sort((a, b) => a - b);
265
+ if (opts.bySecond.length === 0) delete opts.bySecond;
266
+ }
267
+ if (opts.bySetPos) {
268
+ opts.bySetPos = opts.bySetPos.filter((n) => Number.isInteger(n) && n !== 0);
269
+ if (opts.bySetPos.length === 0) delete opts.bySetPos;
270
+ }
271
+ return opts;
162
272
  }
163
273
  rawAdvance(zdt) {
164
274
  const { freq, interval } = this.opts;
@@ -181,38 +291,64 @@ var RRuleTemporal = class {
181
291
  throw new Error(`Unsupported FREQ: ${freq}`);
182
292
  }
183
293
  }
184
- /** Expand one base ZonedDateTime into all BYHOUR × BYMINUTE combinations,
185
- * keeping chronological order. If BYHOUR/BYMINUTE are not present the
186
- * original date is returned unchanged.
294
+ /** Expand one base ZonedDateTime into all BYHOUR × BYMINUTE × BYSECOND
295
+ * combinations, keeping chronological order. If the options are not
296
+ * present the original date is returned unchanged.
187
297
  */
188
- expandByHourMinute(base) {
298
+ expandByTime(base) {
189
299
  const hours = this.opts.byHour ?? [base.hour];
190
300
  const minutes = this.opts.byMinute ?? [base.minute];
301
+ const seconds = this.opts.bySecond ?? [base.second];
191
302
  const out = [];
192
303
  for (const h of hours) {
193
304
  for (const m of minutes) {
194
- out.push(base.with({ hour: h, minute: m }));
305
+ for (const s of seconds) {
306
+ out.push(base.with({ hour: h, minute: m, second: s }));
307
+ }
195
308
  }
196
309
  }
197
310
  return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
198
311
  }
199
312
  nextCandidateSameDate(zdt) {
200
- const { freq, interval = 1, byHour, byMinute } = this.opts;
313
+ const { freq, interval = 1, byHour, byMinute, bySecond } = this.opts;
201
314
  if (freq === "HOURLY" && byHour && byHour.length === 1) {
202
315
  return this.applyTimeOverride(zdt.add({ days: interval }));
203
316
  }
204
317
  if (freq === "MINUTELY" && byMinute && byMinute.length === 1) {
205
318
  return this.applyTimeOverride(zdt.add({ hours: interval }));
206
319
  }
320
+ if (freq === "MINUTELY" && byHour && byHour.length > 1 && !byMinute && interval > 1) {
321
+ const next = zdt.add({ minutes: interval });
322
+ if (byHour.includes(next.hour)) {
323
+ return next;
324
+ }
325
+ const nextHour = byHour.find((h) => h > zdt.hour) || byHour[0];
326
+ if (nextHour && nextHour > zdt.hour) {
327
+ return zdt.with({ hour: nextHour, minute: 0 });
328
+ }
329
+ return this.applyTimeOverride(zdt.add({ days: 1 }));
330
+ }
331
+ if (freq === "SECONDLY" && bySecond && bySecond.length === 1) {
332
+ return this.applyTimeOverride(zdt.add({ minutes: interval })).with({ second: bySecond[0] });
333
+ }
207
334
  if (freq === "SECONDLY" && byMinute && byMinute.length === 1) {
208
335
  const next = zdt.add({ seconds: interval });
209
336
  if (next.minute === byMinute[0]) return next;
210
337
  return this.applyTimeOverride(zdt.add({ hours: interval })).with({ second: 0 });
211
338
  }
339
+ if (bySecond && bySecond.length > 1) {
340
+ const idx = bySecond.indexOf(zdt.second);
341
+ if (idx !== -1 && idx < bySecond.length - 1) {
342
+ return zdt.with({ second: bySecond[idx + 1] });
343
+ }
344
+ }
212
345
  if (byMinute && byMinute.length > 1) {
213
346
  const idx = byMinute.indexOf(zdt.minute);
214
347
  if (idx !== -1 && idx < byMinute.length - 1) {
215
- return zdt.with({ minute: byMinute[idx + 1] });
348
+ return zdt.with({
349
+ minute: byMinute[idx + 1],
350
+ second: bySecond ? bySecond[0] : zdt.second
351
+ });
216
352
  }
217
353
  }
218
354
  if (byHour && byHour.length > 1) {
@@ -220,17 +356,19 @@ var RRuleTemporal = class {
220
356
  if (idx !== -1 && idx < byHour.length - 1) {
221
357
  return zdt.with({
222
358
  hour: byHour[idx + 1],
223
- minute: byMinute ? byMinute[0] : zdt.minute
359
+ minute: byMinute ? byMinute[0] : zdt.minute,
360
+ second: bySecond ? bySecond[0] : zdt.second
224
361
  });
225
362
  }
226
363
  }
227
364
  return this.applyTimeOverride(this.rawAdvance(zdt));
228
365
  }
229
366
  applyTimeOverride(zdt) {
230
- const { byHour, byMinute } = this.opts;
367
+ const { byHour, byMinute, bySecond } = this.opts;
231
368
  let dt = zdt;
232
369
  if (byHour) dt = dt.with({ hour: byHour[0] });
233
370
  if (byMinute) dt = dt.with({ minute: byMinute[0] });
371
+ if (bySecond) dt = dt.with({ second: bySecond[0] });
234
372
  return dt;
235
373
  }
236
374
  computeFirst() {
@@ -260,8 +398,8 @@ var RRuleTemporal = class {
260
398
  zdt = zdt.add({ days: Math.min(...deltas) });
261
399
  }
262
400
  }
263
- const { byHour, byMinute } = this.opts;
264
- if (byHour || byMinute) {
401
+ const { byHour, byMinute, bySecond } = this.opts;
402
+ if (byHour || byMinute || bySecond) {
265
403
  zdt = this.applyTimeOverride(zdt);
266
404
  if (Temporal.Instant.compare(
267
405
  zdt.toInstant(),
@@ -288,7 +426,7 @@ var RRuleTemporal = class {
288
426
  const targetDow = dayMap[tok];
289
427
  const delta = (targetDow - sample.dayOfWeek + 7) % 7;
290
428
  const sameDate = sample.add({ days: delta });
291
- return this.expandByHourMinute(sameDate);
429
+ return this.expandByTime(sameDate);
292
430
  });
293
431
  return occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
294
432
  }
@@ -307,7 +445,7 @@ var RRuleTemporal = class {
307
445
  SU: 7
308
446
  };
309
447
  for (const token of byDay) {
310
- const m = token.match(/^([+-]?\d)?(MO|TU|WE|TH|FR|SA|SU)$/);
448
+ const m = token.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
311
449
  if (!m) continue;
312
450
  const ord = m[1] ? parseInt(m[1], 10) : 0;
313
451
  const weekday = m[2];
@@ -343,7 +481,28 @@ var RRuleTemporal = class {
343
481
  );
344
482
  }
345
483
  matchesAll(zdt) {
346
- return this.matchesByDay(zdt) && this.matchesByMonth(zdt) && this.matchesByMonthDay(zdt);
484
+ return this.matchesByDay(zdt) && this.matchesByMonth(zdt) && this.matchesByMonthDay(zdt) && this.matchesByYearDay(zdt) && this.matchesByWeekNo(zdt);
485
+ }
486
+ matchesByYearDay(zdt) {
487
+ const { byYearDay } = this.opts;
488
+ if (!byYearDay) return true;
489
+ const dayOfYear = zdt.dayOfYear;
490
+ const last = zdt.with({ month: 12, day: 31 }).dayOfYear;
491
+ return byYearDay.some((d) => d > 0 ? dayOfYear === d : dayOfYear === last + d + 1);
492
+ }
493
+ matchesByWeekNo(zdt) {
494
+ const { byWeekNo, wkst } = this.opts;
495
+ if (!byWeekNo) return true;
496
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
497
+ const startDow = dayMap[wkst ?? "MO"];
498
+ const jan1 = zdt.with({ month: 1, day: 1 });
499
+ const delta = (jan1.dayOfWeek - startDow + 7) % 7;
500
+ const firstWeekStart = jan1.subtract({ days: delta });
501
+ const diffDays = zdt.toPlainDate().since(firstWeekStart.toPlainDate()).days;
502
+ const week = Math.floor(diffDays / 7) + 1;
503
+ const lastWeekDiff = zdt.with({ month: 12, day: 31 }).toPlainDate().since(firstWeekStart.toPlainDate()).days;
504
+ const lastWeek = Math.floor(lastWeekDiff / 7) + 1;
505
+ return byWeekNo.some((n) => n > 0 ? week === n : week === lastWeek + n + 1);
347
506
  }
348
507
  options() {
349
508
  return this.opts;
@@ -358,11 +517,15 @@ var RRuleTemporal = class {
358
517
  throw new Error("all() requires iterator when no COUNT/UNTIL");
359
518
  }
360
519
  const dates = [];
520
+ let iterationCount = 0;
361
521
  if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
362
522
  const start = this.originalDtstart;
363
523
  let monthCursor = start.with({ day: 1 });
364
524
  let matchCount2 = 0;
365
525
  outer_month: while (true) {
526
+ if (++iterationCount > this.maxIterations) {
527
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
528
+ }
366
529
  const occs = this.generateMonthlyOccurrences(monthCursor);
367
530
  if (monthCursor.month === start.month && occs.some((o) => Temporal.ZonedDateTime.compare(o, start) < 0)) {
368
531
  monthCursor = monthCursor.add({ months: this.opts.interval });
@@ -373,18 +536,18 @@ var RRuleTemporal = class {
373
536
  if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
374
537
  break outer_month;
375
538
  }
376
- if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
377
- break outer_month;
378
- }
379
539
  if (iterator && !iterator(occ, matchCount2)) {
380
540
  break outer_month;
381
541
  }
382
542
  dates.push(occ);
383
543
  matchCount2++;
544
+ if (this.shouldBreakForCountLimit(matchCount2)) {
545
+ break outer_month;
546
+ }
384
547
  }
385
548
  monthCursor = monthCursor.add({ months: this.opts.interval });
386
549
  }
387
- return dates;
550
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
388
551
  }
389
552
  if (this.opts.freq === "WEEKLY") {
390
553
  const start = this.originalDtstart;
@@ -403,105 +566,215 @@ var RRuleTemporal = class {
403
566
  const delta = (dw - start.dayOfWeek + 7) % 7;
404
567
  return start.add({ days: delta });
405
568
  });
406
- let weekCursor = firstWeekDates.reduce(
569
+ let firstOccurrence = firstWeekDates.reduce(
407
570
  (a, b) => Temporal.ZonedDateTime.compare(a, b) <= 0 ? a : b
408
571
  );
572
+ const wkstDay = dayMap[this.opts.wkst || "MO"] ?? 1;
573
+ const firstOccWeekOffset = (firstOccurrence.dayOfWeek - wkstDay + 7) % 7;
574
+ let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
409
575
  let matchCount2 = 0;
410
576
  outer_week: while (true) {
411
- const baseDow = weekCursor.dayOfWeek;
577
+ if (++iterationCount > this.maxIterations) {
578
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
579
+ }
412
580
  const occs = dows.flatMap((dw) => {
413
- const delta = dw - baseDow;
581
+ const delta = (dw - wkstDay + 7) % 7;
414
582
  const sameDate = weekCursor.add({ days: delta });
415
- return this.expandByHourMinute(sameDate);
583
+ return this.expandByTime(sameDate);
416
584
  }).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
417
585
  for (const occ of occs) {
418
586
  if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
419
587
  if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
420
588
  break outer_week;
421
589
  }
422
- if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
423
- break outer_week;
424
- }
425
590
  if (iterator && !iterator(occ, matchCount2)) {
426
591
  break outer_week;
427
592
  }
428
593
  dates.push(occ);
429
594
  matchCount2++;
595
+ if (this.shouldBreakForCountLimit(matchCount2)) {
596
+ break outer_week;
597
+ }
430
598
  }
431
599
  weekCursor = weekCursor.add({ weeks: this.opts.interval });
432
600
  }
433
- return dates;
601
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
434
602
  }
435
603
  if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
436
604
  const start = this.originalDtstart;
437
605
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
438
- let i = 0;
606
+ let yearOffset = 0;
607
+ let matchCount2 = 0;
439
608
  while (true) {
440
- const year = start.year + i * this.opts.interval;
441
- const month = months[i % months.length];
442
- let occ = start.with({ year, month });
443
- occ = this.applyTimeOverride(occ);
444
- if (i === 0 && Temporal.ZonedDateTime.compare(occ, start) < 0) {
445
- i++;
446
- continue;
609
+ if (++iterationCount > this.maxIterations) {
610
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
447
611
  }
448
- if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
449
- break;
450
- }
451
- if (this.opts.count !== void 0 && i >= this.opts.count) {
452
- break;
453
- }
454
- if (iterator && !iterator(occ, i)) {
455
- break;
612
+ const year = start.year + yearOffset * this.opts.interval;
613
+ for (const month of months) {
614
+ let occ = start.with({ year, month });
615
+ occ = this.applyTimeOverride(occ);
616
+ if (Temporal.ZonedDateTime.compare(occ, start) < 0) {
617
+ continue;
618
+ }
619
+ if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
620
+ return dates;
621
+ }
622
+ if (iterator && !iterator(occ, matchCount2)) {
623
+ return dates;
624
+ }
625
+ dates.push(occ);
626
+ matchCount2++;
627
+ if (this.shouldBreakForCountLimit(matchCount2)) {
628
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
629
+ }
456
630
  }
457
- dates.push(occ);
458
- i++;
631
+ yearOffset++;
459
632
  }
460
- return dates;
633
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
461
634
  }
462
635
  if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
463
636
  const start = this.originalDtstart;
464
637
  let yearCursor = start.with({ month: 1, day: 1 });
465
638
  let matchCount2 = 0;
466
639
  outer_year: while (true) {
640
+ if (++iterationCount > this.maxIterations) {
641
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
642
+ }
467
643
  const occs = this.generateYearlyOccurrences(yearCursor);
468
644
  for (const occ of occs) {
469
645
  if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
470
646
  if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
471
647
  break outer_year;
472
648
  }
473
- if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
649
+ if (iterator && !iterator(occ, matchCount2)) {
474
650
  break outer_year;
475
651
  }
476
- if (iterator && !iterator(occ, matchCount2)) {
652
+ dates.push(occ);
653
+ matchCount2++;
654
+ if (this.shouldBreakForCountLimit(matchCount2)) {
477
655
  break outer_year;
478
656
  }
657
+ }
658
+ yearCursor = yearCursor.add({ years: this.opts.interval });
659
+ }
660
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
661
+ }
662
+ if (this.opts.freq === "YEARLY" && (this.opts.byYearDay || this.opts.byWeekNo)) {
663
+ const start = this.originalDtstart;
664
+ let yearCursor = start.with({ month: 1, day: 1 });
665
+ let matchCount2 = 0;
666
+ outer_year2: while (true) {
667
+ if (++iterationCount > this.maxIterations) {
668
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
669
+ }
670
+ const occs = this.generateYearlyOccurrences(yearCursor);
671
+ for (const occ of occs) {
672
+ if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
673
+ if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
674
+ break outer_year2;
675
+ }
676
+ if (iterator && !iterator(occ, matchCount2)) {
677
+ break outer_year2;
678
+ }
479
679
  dates.push(occ);
480
680
  matchCount2++;
681
+ if (this.shouldBreakForCountLimit(matchCount2)) {
682
+ break outer_year2;
683
+ }
481
684
  }
482
685
  yearCursor = yearCursor.add({ years: this.opts.interval });
483
686
  }
484
- return dates;
687
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
485
688
  }
486
689
  let current = this.computeFirst();
487
690
  let matchCount = 0;
488
691
  while (true) {
692
+ if (++iterationCount > this.maxIterations) {
693
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
694
+ }
489
695
  if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
490
696
  break;
491
697
  }
492
698
  if (this.matchesAll(current)) {
493
- if (this.opts.count !== void 0 && matchCount >= this.opts.count) {
494
- break;
495
- }
496
699
  if (iterator && !iterator(current, matchCount)) {
497
700
  break;
498
701
  }
499
702
  dates.push(current);
500
703
  matchCount++;
704
+ if (this.shouldBreakForCountLimit(matchCount)) {
705
+ break;
706
+ }
501
707
  }
502
708
  current = this.nextCandidateSameDate(current);
503
709
  }
504
- return dates;
710
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
711
+ }
712
+ /**
713
+ * Converts rDate entries to ZonedDateTime and merges with existing dates.
714
+ * @param dates - Array of dates to merge with
715
+ * @returns Merged and deduplicated array of dates
716
+ */
717
+ mergeAndDeduplicateRDates(dates) {
718
+ if (!this.opts.rDate) return dates;
719
+ dates.push(...this.opts.rDate);
720
+ dates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
721
+ const dedup = [];
722
+ for (const d of dates) {
723
+ if (dedup.length === 0 || Temporal.ZonedDateTime.compare(d, dedup[dedup.length - 1]) !== 0) {
724
+ dedup.push(d);
725
+ }
726
+ }
727
+ return dedup;
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
+ }
742
+ /**
743
+ * Applies count limit and merges rDates with the rule-generated dates.
744
+ * @param dates - Array of dates generated by the rule
745
+ * @param iterator - Optional iterator function
746
+ * @returns Final array of dates after merging and applying count limit
747
+ */
748
+ applyCountLimitAndMergeRDates(dates, iterator) {
749
+ const merged = this.mergeAndDeduplicateRDates(dates);
750
+ const excluded = this.excludeExDates(merged);
751
+ if (this.opts.count !== void 0) {
752
+ let finalCount = 0;
753
+ const finalDates = [];
754
+ for (const d of excluded) {
755
+ if (finalCount >= this.opts.count) break;
756
+ if (iterator && !iterator(d, finalCount)) break;
757
+ finalDates.push(d);
758
+ finalCount++;
759
+ }
760
+ return finalDates;
761
+ }
762
+ return excluded;
763
+ }
764
+ /**
765
+ * Checks if the count limit should break the loop based on rDate presence.
766
+ * @param matchCount - Current number of matches
767
+ * @returns true if the loop should break
768
+ */
769
+ shouldBreakForCountLimit(matchCount) {
770
+ if (this.opts.count === void 0) return false;
771
+ if (!this.opts.rDate) {
772
+ return matchCount >= this.opts.count;
773
+ }
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;
505
778
  }
506
779
  /**
507
780
  * Returns all occurrences of the rule within a specified time window.
@@ -514,60 +787,96 @@ var RRuleTemporal = class {
514
787
  const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
515
788
  const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
516
789
  const results = [];
790
+ let iterationCount = 0;
517
791
  if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
518
792
  let monthCursor = this.computeFirst().with({ day: 1 });
519
793
  outer: while (true) {
794
+ if (++iterationCount > this.maxIterations) {
795
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
796
+ }
520
797
  const occs = this.generateMonthlyOccurrences(monthCursor);
521
798
  for (const occ of occs) {
522
799
  const inst = occ.toInstant();
523
800
  if (inc ? Temporal.Instant.compare(inst, endInst) > 0 : Temporal.Instant.compare(inst, endInst) >= 0) {
524
801
  break outer;
525
802
  }
526
- if (Temporal.Instant.compare(inst, startInst) >= 0) {
803
+ const startOk = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
804
+ if (startOk) {
527
805
  results.push(occ);
528
806
  }
529
807
  }
530
808
  monthCursor = monthCursor.add({ months: this.opts.interval });
531
809
  }
532
- return results;
810
+ return this.mergeRDates(results, startInst, endInst, inc);
533
811
  }
534
812
  if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
535
813
  const start = this.originalDtstart;
536
814
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
537
- let i = 0;
815
+ let yearOffset = 0;
538
816
  outer: while (true) {
539
- const year = start.year + i * this.opts.interval;
540
- const month = months[i % months.length];
541
- let occ = start.with({ year, month });
542
- occ = this.applyTimeOverride(occ);
543
- const inst = occ.toInstant();
544
- if (inc ? Temporal.Instant.compare(inst, endInst) > 0 : Temporal.Instant.compare(inst, endInst) >= 0) {
545
- break;
817
+ if (++iterationCount > this.maxIterations) {
818
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
546
819
  }
547
- if (Temporal.Instant.compare(inst, startInst) >= 0) {
548
- results.push(occ);
820
+ const year = start.year + yearOffset * this.opts.interval;
821
+ for (const month of months) {
822
+ let occ = start.with({ year, month });
823
+ occ = this.applyTimeOverride(occ);
824
+ const inst = occ.toInstant();
825
+ if (inc ? Temporal.Instant.compare(inst, endInst) > 0 : Temporal.Instant.compare(inst, endInst) >= 0) {
826
+ break outer;
827
+ }
828
+ const startOk = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
829
+ if (startOk) {
830
+ results.push(occ);
831
+ }
549
832
  }
550
- i++;
833
+ yearOffset++;
551
834
  }
552
- return results;
835
+ return this.mergeRDates(results, startInst, endInst, inc);
553
836
  }
554
837
  if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
555
838
  const start = this.originalDtstart;
556
839
  let yearCursor = start.with({ month: 1, day: 1 });
557
840
  outer_year: while (true) {
841
+ if (++iterationCount > this.maxIterations) {
842
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
843
+ }
558
844
  const occs = this.generateYearlyOccurrences(yearCursor);
559
845
  for (const occ of occs) {
560
846
  const inst = occ.toInstant();
561
847
  if (inc ? Temporal.Instant.compare(inst, endInst) > 0 : Temporal.Instant.compare(inst, endInst) >= 0) {
562
848
  break outer_year;
563
849
  }
564
- if (Temporal.Instant.compare(inst, startInst) >= 0) {
850
+ const startOk = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
851
+ if (startOk) {
852
+ results.push(occ);
853
+ }
854
+ }
855
+ yearCursor = yearCursor.add({ years: this.opts.interval });
856
+ }
857
+ return this.mergeRDates(results, startInst, endInst, inc);
858
+ }
859
+ if (this.opts.freq === "YEARLY" && (this.opts.byYearDay || this.opts.byWeekNo)) {
860
+ const start = this.originalDtstart;
861
+ let yearCursor = start.with({ month: 1, day: 1 });
862
+ outer_year2: while (true) {
863
+ if (++iterationCount > this.maxIterations) {
864
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
865
+ }
866
+ const occs = this.generateYearlyOccurrences(yearCursor);
867
+ for (const occ of occs) {
868
+ const inst = occ.toInstant();
869
+ if (inc ? Temporal.Instant.compare(inst, endInst) > 0 : Temporal.Instant.compare(inst, endInst) >= 0) {
870
+ break outer_year2;
871
+ }
872
+ const startOk = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
873
+ if (startOk) {
565
874
  results.push(occ);
566
875
  }
567
876
  }
568
877
  yearCursor = yearCursor.add({ years: this.opts.interval });
569
878
  }
570
- return results;
879
+ return this.mergeRDates(results, startInst, endInst, inc);
571
880
  }
572
881
  if (this.opts.freq === "WEEKLY") {
573
882
  const startInst2 = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
@@ -575,34 +884,42 @@ var RRuleTemporal = class {
575
884
  let weekCursor = this.computeFirst();
576
885
  const results2 = [];
577
886
  outer: while (true) {
887
+ if (++iterationCount > this.maxIterations) {
888
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
889
+ }
578
890
  const occs = this.generateWeeklyOccurrences(weekCursor);
579
891
  for (const occ of occs) {
580
892
  const inst = occ.toInstant();
581
893
  if (inc ? Temporal.Instant.compare(inst, endInst2) > 0 : Temporal.Instant.compare(inst, endInst2) >= 0) {
582
894
  break outer;
583
895
  }
584
- if (Temporal.Instant.compare(inst, startInst2) >= 0) {
896
+ const startOk = inc ? Temporal.Instant.compare(inst, startInst2) >= 0 : Temporal.Instant.compare(inst, startInst2) > 0;
897
+ if (startOk) {
585
898
  results2.push(occ);
586
899
  }
587
900
  }
588
901
  weekCursor = weekCursor.add({ weeks: this.opts.interval });
589
902
  }
590
- return results2;
903
+ return this.mergeRDates(results2, startInst2, endInst2, inc);
591
904
  }
592
905
  let current = this.computeFirst();
593
906
  while (true) {
907
+ if (++iterationCount > this.maxIterations) {
908
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in between()`);
909
+ }
594
910
  const inst = current.toInstant();
595
911
  if (inc) {
596
912
  if (Temporal.Instant.compare(inst, endInst) > 0) break;
597
913
  } else {
598
914
  if (Temporal.Instant.compare(inst, endInst) >= 0) break;
599
915
  }
600
- if (Temporal.Instant.compare(inst, startInst) >= 0 && this.matchesAll(current)) {
916
+ const startOk = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
917
+ if (startOk && this.matchesAll(current)) {
601
918
  results.push(current);
602
919
  }
603
920
  current = this.nextCandidateSameDate(current);
604
921
  }
605
- return results;
922
+ return this.mergeRDates(results, startInst, endInst, inc);
606
923
  }
607
924
  /**
608
925
  * Returns the next occurrence of the rule after a specified date.
@@ -758,12 +1075,15 @@ var RRuleTemporal = class {
758
1075
  if (byMonthDay && byMonthDay.length > 0) {
759
1076
  byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
760
1077
  }
761
- if (!byDay && byMonthDayHits.length) {
1078
+ if (!byDay && byMonthDay && byMonthDay.length > 0) {
1079
+ if (byMonthDayHits.length === 0) {
1080
+ return [];
1081
+ }
762
1082
  const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
763
- return dates.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1083
+ return dates.flatMap((z) => this.expandByTime(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
764
1084
  }
765
1085
  if (!byDay) {
766
- return this.expandByHourMinute(sample);
1086
+ return this.expandByTime(sample);
767
1087
  }
768
1088
  const dayMap = {
769
1089
  MO: 1,
@@ -775,7 +1095,7 @@ var RRuleTemporal = class {
775
1095
  SU: 7
776
1096
  };
777
1097
  const tokens = byDay.map((tok) => {
778
- const m = tok.match(/^([+-]?\d)?(MO|TU|WE|TH|FR|SA|SU)$/);
1098
+ const m = tok.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
779
1099
  if (!m) return null;
780
1100
  return { ord: m[1] ? parseInt(m[1], 10) : 0, wd: dayMap[m[2]] };
781
1101
  }).filter((x) => x !== null);
@@ -799,11 +1119,16 @@ var RRuleTemporal = class {
799
1119
  }
800
1120
  }
801
1121
  let finalDays = byDayHits;
802
- if (byMonthDayHits.length) {
1122
+ if (byMonthDay && byMonthDay.length > 0) {
1123
+ if (byMonthDayHits.length === 0) {
1124
+ return [];
1125
+ }
803
1126
  finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
804
1127
  }
805
1128
  const hits = finalDays.map((d) => sample.with({ day: d }));
806
- return hits.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1129
+ let expanded = hits.flatMap((z) => this.expandByTime(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1130
+ expanded = this.applyBySetPos(expanded);
1131
+ return expanded;
807
1132
  }
808
1133
  /**
809
1134
  * Given any date in a year, return all ZonedDateTimes in that year matching
@@ -812,11 +1137,114 @@ var RRuleTemporal = class {
812
1137
  */
813
1138
  generateYearlyOccurrences(sample) {
814
1139
  const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : [this.originalDtstart.month];
815
- const occs = months.flatMap((m) => {
816
- const monthSample = sample.with({ month: m, day: 1 });
817
- return this.generateMonthlyOccurrences(monthSample);
818
- });
819
- return occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1140
+ let occs = [];
1141
+ if (this.opts.byDay && this.opts.byDay.some((t) => /\d{2}/.test(t))) {
1142
+ const dayMap = {
1143
+ MO: 1,
1144
+ TU: 2,
1145
+ WE: 3,
1146
+ TH: 4,
1147
+ FR: 5,
1148
+ SA: 6,
1149
+ SU: 7
1150
+ };
1151
+ for (const tok of this.opts.byDay) {
1152
+ const m = tok.match(/^([+-]?\d{1,2})(MO|TU|WE|TH|FR|SA|SU)$/);
1153
+ if (!m) continue;
1154
+ const ord = parseInt(m[1], 10);
1155
+ const wd = dayMap[m[2]];
1156
+ let dt;
1157
+ if (ord > 0) {
1158
+ const jan1 = sample.with({ month: 1, day: 1 });
1159
+ const delta = (wd - jan1.dayOfWeek + 7) % 7;
1160
+ dt = jan1.add({ days: delta + 7 * (ord - 1) });
1161
+ } else {
1162
+ const dec31 = sample.with({ month: 12, day: 31 });
1163
+ const delta = (dec31.dayOfWeek - wd + 7) % 7;
1164
+ dt = dec31.subtract({ days: delta + 7 * (-ord - 1) });
1165
+ }
1166
+ if (!this.opts.byMonth || this.opts.byMonth.includes(dt.month)) {
1167
+ occs.push(...this.expandByTime(dt));
1168
+ }
1169
+ }
1170
+ } else if (!this.opts.byYearDay && !this.opts.byWeekNo) {
1171
+ occs = months.flatMap((m) => {
1172
+ const monthSample = sample.with({ month: m, day: 1 });
1173
+ return this.generateMonthlyOccurrences(monthSample);
1174
+ });
1175
+ }
1176
+ if (this.opts.byYearDay) {
1177
+ const last = sample.with({ month: 12, day: 31 }).dayOfYear;
1178
+ for (const d of this.opts.byYearDay) {
1179
+ const dayNum = d > 0 ? d : last + d + 1;
1180
+ const dt = sample.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1181
+ if (!this.opts.byMonth || this.opts.byMonth.includes(dt.month)) {
1182
+ occs.push(...this.expandByTime(dt));
1183
+ }
1184
+ }
1185
+ }
1186
+ if (this.opts.byWeekNo) {
1187
+ const dayMap = {
1188
+ MO: 1,
1189
+ TU: 2,
1190
+ WE: 3,
1191
+ TH: 4,
1192
+ FR: 5,
1193
+ SA: 6,
1194
+ SU: 7
1195
+ };
1196
+ const wkst = dayMap[this.opts.wkst || "MO"];
1197
+ const jan1 = sample.with({ month: 1, day: 1 });
1198
+ const delta = (jan1.dayOfWeek - wkst + 7) % 7;
1199
+ const firstWeekStart = jan1.subtract({ days: delta });
1200
+ const lastWeekDiff = sample.with({ month: 12, day: 31 }).toPlainDate().since(firstWeekStart.toPlainDate()).days;
1201
+ const lastWeek = Math.floor(lastWeekDiff / 7) + 1;
1202
+ const tokens = this.opts.byDay?.length ? this.opts.byDay.map((tok) => tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)?.[1]) : [this.opts.wkst || "MO"];
1203
+ for (const weekNo of this.opts.byWeekNo) {
1204
+ const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
1205
+ const weekStart = firstWeekStart.add({ weeks: weekIndex });
1206
+ for (const tok of tokens) {
1207
+ if (!tok) continue;
1208
+ const targetDow = dayMap[tok];
1209
+ const inst = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
1210
+ if (!this.opts.byMonth || this.opts.byMonth.includes(inst.month)) {
1211
+ occs.push(...this.expandByTime(inst));
1212
+ }
1213
+ }
1214
+ }
1215
+ }
1216
+ occs = occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1217
+ occs = this.applyBySetPos(occs);
1218
+ return occs;
1219
+ }
1220
+ applyBySetPos(list2) {
1221
+ const { bySetPos } = this.opts;
1222
+ if (!bySetPos || !bySetPos.length) return list2;
1223
+ const sorted = [...list2].sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1224
+ const out = [];
1225
+ const len = sorted.length;
1226
+ for (const pos of bySetPos) {
1227
+ const idx = pos > 0 ? pos - 1 : len + pos;
1228
+ if (idx >= 0 && idx < len) out.push(sorted[idx]);
1229
+ }
1230
+ return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1231
+ }
1232
+ mergeRDates(list2, startInst, endInst, inc) {
1233
+ if (!this.opts.rDate) return this.excludeExDates(list2);
1234
+ for (const z of this.opts.rDate) {
1235
+ const inst = z.toInstant();
1236
+ const startOk = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
1237
+ const endOk = inc ? Temporal.Instant.compare(inst, endInst) <= 0 : Temporal.Instant.compare(inst, endInst) < 0;
1238
+ if (startOk && endOk) list2.push(z);
1239
+ }
1240
+ list2.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1241
+ const dedup = [];
1242
+ for (const d of list2) {
1243
+ if (dedup.length === 0 || Temporal.ZonedDateTime.compare(d, dedup[dedup.length - 1]) !== 0) {
1244
+ dedup.push(d);
1245
+ }
1246
+ }
1247
+ return this.excludeExDates(dedup);
820
1248
  }
821
1249
  };
822
1250
  export {