rrule-temporal 1.1.2 → 1.1.4

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/totext.cjs CHANGED
@@ -43,25 +43,41 @@ var import_polyfill = require("@js-temporal/polyfill");
43
43
  function unfoldLine(foldedLine) {
44
44
  return foldedLine.replace(/\r?\n[ \t]/g, "");
45
45
  }
46
- function parseDateValues(dateValues, tzid, valueType) {
46
+ function parseIcsDateTime(dateStr, tzid, valueType) {
47
+ const isDate = valueType === "DATE" || !dateStr.includes("T");
48
+ const isoDate = `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
49
+ if (isDate) {
50
+ return import_polyfill.Temporal.PlainDate.from(isoDate).toZonedDateTime({ timeZone: tzid });
51
+ }
52
+ if (dateStr.endsWith("Z")) {
53
+ const iso = `${isoDate}T${dateStr.slice(9, 15)}Z`;
54
+ return import_polyfill.Temporal.Instant.from(iso).toZonedDateTimeISO(tzid || "UTC");
55
+ } else {
56
+ const iso = `${isoDate}T${dateStr.slice(9)}`;
57
+ return import_polyfill.Temporal.PlainDateTime.from(iso).toZonedDateTime(tzid);
58
+ }
59
+ }
60
+ function parseDateLines(lines, linePrefix, defaultTzid) {
47
61
  const dates = [];
48
- for (const dateValue of dateValues) {
49
- const isDate = valueType === "DATE" || !dateValue.includes("T");
50
- if (isDate) {
51
- const isoDate = `${dateValue.slice(0, 4)}-${dateValue.slice(4, 6)}-${dateValue.slice(6, 8)}`;
52
- dates.push(import_polyfill.Temporal.PlainDate.from(isoDate).toZonedDateTime({ timeZone: tzid }));
53
- } else {
54
- if (/Z$/.test(dateValue)) {
55
- const iso = `${dateValue.slice(0, 4)}-${dateValue.slice(4, 6)}-${dateValue.slice(6, 8)}T${dateValue.slice(9, 15)}Z`;
56
- dates.push(import_polyfill.Temporal.Instant.from(iso).toZonedDateTimeISO(tzid || "UTC"));
57
- } else {
58
- const isoDate = `${dateValue.slice(0, 4)}-${dateValue.slice(4, 6)}-${dateValue.slice(6, 8)}T${dateValue.slice(9)}`;
59
- dates.push(import_polyfill.Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid));
60
- }
62
+ const regex = new RegExp(`^${linePrefix}(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)`, "i");
63
+ for (const line of lines) {
64
+ const match = line.match(regex);
65
+ if (match) {
66
+ const [, valueType, tzid, dateValuesStr] = match;
67
+ const timezone = tzid || defaultTzid;
68
+ const dateValues = dateValuesStr.split(",");
69
+ dates.push(...dateValues.map((dateValue) => parseIcsDateTime(dateValue, timezone, valueType)));
61
70
  }
62
71
  }
63
72
  return dates;
64
73
  }
74
+ function parseNumberArray(val, sort = false) {
75
+ const arr = val.split(",").map((n) => parseInt(n, 10));
76
+ if (sort) {
77
+ return arr.sort((a, b) => a - b);
78
+ }
79
+ return arr;
80
+ }
65
81
  function parseRRuleString(input, targetTimezone) {
66
82
  var _a;
67
83
  const unfoldedInput = unfoldLine(input).trim();
@@ -80,26 +96,10 @@ function parseRRuleString(input, targetTimezone) {
80
96
  if (!dtMatch) throw new Error("Invalid DTSTART in ICS snippet");
81
97
  const [, valueType, dtTzid, dtValue] = dtMatch;
82
98
  tzid = (_a = dtTzid != null ? dtTzid : targetTimezone) != null ? _a : tzid;
83
- dtstart = parseDateValues([dtValue], tzid, valueType)[0];
99
+ dtstart = parseIcsDateTime(dtValue, tzid, valueType);
84
100
  rruleLine = rrLine;
85
- for (const exLine of exLines) {
86
- const exMatch = exLine.match(/EXDATE(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)/i);
87
- if (exMatch) {
88
- const [, valueType2, exTzid, dateValuesStr] = exMatch;
89
- const exTimezone = exTzid || tzid;
90
- const dateValues = dateValuesStr.split(",");
91
- exDate.push(...parseDateValues(dateValues, exTimezone, valueType2));
92
- }
93
- }
94
- for (const rLine of rLines) {
95
- const rMatch = rLine.match(/RDATE(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)/i);
96
- if (rMatch) {
97
- const [, valueType2, rTzid, dateValuesStr] = rMatch;
98
- const rTimezone = rTzid || tzid;
99
- const dateValues = dateValuesStr.split(",");
100
- rDate.push(...parseDateValues(dateValues, rTimezone, valueType2));
101
- }
102
- }
101
+ exDate = parseDateLines(exLines, "EXDATE", tzid);
102
+ rDate = parseDateLines(rLines, "RDATE", tzid);
103
103
  } else {
104
104
  throw new Error("dtstart required when parsing RRULE alone");
105
105
  }
@@ -124,44 +124,38 @@ function parseRRuleString(input, targetTimezone) {
124
124
  opts.count = parseInt(val, 10);
125
125
  break;
126
126
  case "UNTIL": {
127
- if (/Z$/.test(val)) {
128
- const iso = `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6, 8)}T${val.slice(9, 15)}Z`;
129
- opts.until = import_polyfill.Temporal.Instant.from(iso).toZonedDateTimeISO(tzid || "UTC");
130
- } else {
131
- const iso = `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6, 8)}T${val.slice(9, 15)}`;
132
- opts.until = import_polyfill.Temporal.PlainDateTime.from(iso).toZonedDateTime(tzid || "UTC");
133
- if (tzid !== "UTC") {
134
- throw new Error("UNTIL rule part MUST always be specified as a date with UTC time");
135
- }
127
+ opts.until = parseIcsDateTime(val, tzid || "UTC");
128
+ if (!val.endsWith("Z") && tzid !== "UTC") {
129
+ throw new Error("UNTIL rule part MUST always be specified as a date with UTC time");
136
130
  }
137
131
  break;
138
132
  }
139
133
  case "BYHOUR":
140
- opts.byHour = val.split(",").map((n) => parseInt(n, 10)).sort((a, b) => a - b);
134
+ opts.byHour = parseNumberArray(val, true);
141
135
  break;
142
136
  case "BYMINUTE":
143
- opts.byMinute = val.split(",").map((n) => parseInt(n, 10)).sort((a, b) => a - b);
137
+ opts.byMinute = parseNumberArray(val, true);
138
+ break;
139
+ case "BYSECOND":
140
+ opts.bySecond = parseNumberArray(val, true);
144
141
  break;
145
142
  case "BYDAY":
146
143
  opts.byDay = val.split(",");
147
144
  break;
148
145
  case "BYMONTH":
149
- opts.byMonth = val.split(",").map((n) => parseInt(n, 10));
146
+ opts.byMonth = parseNumberArray(val);
150
147
  break;
151
148
  case "BYMONTHDAY":
152
- opts.byMonthDay = val.split(",").map((n) => parseInt(n, 10));
153
- break;
154
- case "BYSECOND":
155
- opts.bySecond = val.split(",").map((n) => parseInt(n, 10)).sort((a, b) => a - b);
149
+ opts.byMonthDay = parseNumberArray(val);
156
150
  break;
157
151
  case "BYYEARDAY":
158
- opts.byYearDay = val.split(",").map((n) => parseInt(n, 10));
152
+ opts.byYearDay = parseNumberArray(val);
159
153
  break;
160
154
  case "BYWEEKNO":
161
- opts.byWeekNo = val.split(",").map((n) => parseInt(n, 10));
155
+ opts.byWeekNo = parseNumberArray(val);
162
156
  break;
163
157
  case "BYSETPOS":
164
- opts.bySetPos = val.split(",").map((n) => parseInt(n, 10));
158
+ opts.bySetPos = parseNumberArray(val);
165
159
  break;
166
160
  case "WKST":
167
161
  opts.wkst = val;
@@ -200,46 +194,44 @@ var RRuleTemporal = class _RRuleTemporal {
200
194
  this.maxIterations = (_d = manual.maxIterations) != null ? _d : 1e4;
201
195
  this.includeDtstart = (_e = manual.includeDtstart) != null ? _e : false;
202
196
  }
203
- sanitizeOpts(opts) {
197
+ sanitizeNumericArray(arr, min, max, allowZero = false, sort = false) {
198
+ if (!arr) return void 0;
199
+ const sanitized = arr.filter((n) => Number.isInteger(n) && n >= min && n <= max && (allowZero || n !== 0));
200
+ if (sanitized.length === 0) return void 0;
201
+ return sort ? sanitized.sort((a, b) => a - b) : sanitized;
202
+ }
203
+ sanitizeByDay(byDay) {
204
204
  const validDay = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/;
205
- if (opts.byDay) {
206
- opts.byDay = opts.byDay.filter((d) => validDay.test(d));
207
- if (opts.byDay.length === 0) delete opts.byDay;
208
- }
209
- if (opts.byMonth) {
210
- opts.byMonth = opts.byMonth.filter((n) => Number.isInteger(n) && n >= 1 && n <= 12);
211
- if (opts.byMonth.length === 0) delete opts.byMonth;
212
- }
213
- if (opts.byMonthDay) {
214
- opts.byMonthDay = opts.byMonthDay.filter((n) => Number.isInteger(n) && n !== 0 && n >= -31 && n <= 31);
215
- if (opts.byMonthDay.length === 0) delete opts.byMonthDay;
216
- }
217
- if (opts.byYearDay) {
218
- opts.byYearDay = opts.byYearDay.filter((n) => Number.isInteger(n) && n !== 0 && n >= -366 && n <= 366);
219
- if (opts.byYearDay.length === 0) delete opts.byYearDay;
220
- }
221
- if (opts.byWeekNo) {
222
- opts.byWeekNo = opts.byWeekNo.filter((n) => Number.isInteger(n) && n !== 0 && n >= -53 && n <= 53);
223
- if (opts.byWeekNo.length === 0) delete opts.byWeekNo;
224
- }
225
- if (opts.byHour) {
226
- opts.byHour = opts.byHour.filter((n) => Number.isInteger(n) && n >= 0 && n <= 23).sort((a, b) => a - b);
227
- if (opts.byHour.length === 0) delete opts.byHour;
228
- }
229
- if (opts.byMinute) {
230
- opts.byMinute = opts.byMinute.filter((n) => Number.isInteger(n) && n >= 0 && n <= 59).sort((a, b) => a - b);
231
- if (opts.byMinute.length === 0) delete opts.byMinute;
232
- }
233
- if (opts.bySecond) {
234
- opts.bySecond = opts.bySecond.filter((n) => Number.isInteger(n) && n >= 0 && n <= 59).sort((a, b) => a - b);
235
- if (opts.bySecond.length === 0) delete opts.bySecond;
205
+ const days = (byDay != null ? byDay : []).filter((day) => day && typeof day === "string");
206
+ for (const day of days) {
207
+ const match = day.match(validDay);
208
+ if (!match) {
209
+ throw new Error(`Invalid BYDAY value: ${day}`);
210
+ }
211
+ const ord = match[1];
212
+ if (ord) {
213
+ const ordInt = parseInt(ord, 10);
214
+ if (ordInt === 0) {
215
+ throw new Error(`Invalid BYDAY value: ${day}`);
216
+ }
217
+ }
236
218
  }
219
+ return days.length > 0 ? days : void 0;
220
+ }
221
+ sanitizeOpts(opts) {
222
+ opts.byDay = this.sanitizeByDay(opts.byDay);
223
+ opts.byMonth = this.sanitizeNumericArray(opts.byMonth, 1, 12, false, false);
224
+ opts.byMonthDay = this.sanitizeNumericArray(opts.byMonthDay, -31, 31, false, false);
225
+ opts.byYearDay = this.sanitizeNumericArray(opts.byYearDay, -366, 366, false, false);
226
+ opts.byWeekNo = this.sanitizeNumericArray(opts.byWeekNo, -53, 53, false, false);
227
+ opts.byHour = this.sanitizeNumericArray(opts.byHour, 0, 23, true, true);
228
+ opts.byMinute = this.sanitizeNumericArray(opts.byMinute, 0, 59, true, true);
229
+ opts.bySecond = this.sanitizeNumericArray(opts.bySecond, 0, 59, true, true);
237
230
  if (opts.bySetPos) {
238
231
  if (opts.bySetPos.some((p) => p === 0)) {
239
232
  throw new Error("bySetPos may not contain 0");
240
233
  }
241
- opts.bySetPos = opts.bySetPos.filter((n) => Number.isInteger(n) && n !== 0);
242
- if (opts.bySetPos.length === 0) delete opts.bySetPos;
234
+ opts.bySetPos = this.sanitizeNumericArray(opts.bySetPos, -Infinity, Infinity, false, false);
243
235
  }
244
236
  return opts;
245
237
  }
@@ -254,8 +246,14 @@ var RRuleTemporal = class _RRuleTemporal {
254
246
  return zdt.add({ months: interval });
255
247
  case "YEARLY":
256
248
  return zdt.add({ years: interval });
257
- case "HOURLY":
258
- return zdt.add({ hours: interval });
249
+ case "HOURLY": {
250
+ const originalHour = zdt.hour;
251
+ let next = zdt.add({ hours: interval });
252
+ if (next.hour === originalHour && interval === 1) {
253
+ next = next.add({ hours: interval });
254
+ }
255
+ return next;
256
+ }
259
257
  case "MINUTELY":
260
258
  return zdt.add({ minutes: interval });
261
259
  case "SECONDLY":
@@ -291,30 +289,57 @@ var RRuleTemporal = class _RRuleTemporal {
291
289
  if (freq === "MINUTELY" && byMinute && byMinute.length === 1) {
292
290
  return this.applyTimeOverride(zdt.add({ hours: interval }));
293
291
  }
294
- if (freq === "MINUTELY" && byHour && byHour.length > 1 && !byMinute && interval > 1) {
292
+ if (bySecond && bySecond.length > 1) {
293
+ const idx = bySecond.indexOf(zdt.second);
294
+ if (idx !== -1 && idx < bySecond.length - 1) {
295
+ return zdt.with({ second: bySecond[idx + 1] });
296
+ }
297
+ }
298
+ if (freq === "MINUTELY" && byHour && byHour.length > 1 && !byMinute) {
295
299
  const next = zdt.add({ minutes: interval });
296
300
  if (byHour.includes(next.hour)) {
297
- return next;
301
+ return next.with({ second: bySecond ? bySecond[0] : zdt.second });
298
302
  }
299
303
  const nextHour = byHour.find((h) => h > zdt.hour) || byHour[0];
300
304
  if (nextHour && nextHour > zdt.hour) {
301
- return zdt.with({ hour: nextHour, minute: 0 });
305
+ return zdt.with({ hour: nextHour, minute: 0, second: bySecond ? bySecond[0] : zdt.second });
302
306
  }
303
307
  return this.applyTimeOverride(zdt.add({ days: 1 }));
304
308
  }
305
- if (freq === "SECONDLY" && bySecond && bySecond.length === 1) {
306
- return this.applyTimeOverride(zdt.add({ minutes: interval })).with({ second: bySecond[0] });
307
- }
308
- if (freq === "SECONDLY" && byMinute && byMinute.length === 1) {
309
- const next = zdt.add({ seconds: interval });
310
- if (next.minute === byMinute[0]) return next;
311
- return this.applyTimeOverride(zdt.add({ hours: interval })).with({ second: 0 });
312
- }
313
- if (bySecond && bySecond.length > 1) {
314
- const idx = bySecond.indexOf(zdt.second);
315
- if (idx !== -1 && idx < bySecond.length - 1) {
316
- return zdt.with({ second: bySecond[idx + 1] });
309
+ if (freq === "SECONDLY") {
310
+ let candidate = zdt;
311
+ if (bySecond && bySecond.length > 0) {
312
+ const nextSecondInList = bySecond.find((s) => s > candidate.second);
313
+ if (nextSecondInList !== void 0) {
314
+ return candidate.with({ second: nextSecondInList });
315
+ }
316
+ candidate = candidate.with({ second: bySecond[0] }).add({ minutes: 1 });
317
+ } else {
318
+ candidate = candidate.add({ seconds: interval });
317
319
  }
320
+ if (byMinute && byMinute.length > 0) {
321
+ if (!byMinute.includes(candidate.minute) || candidate.minute === zdt.minute && candidate.second < zdt.second) {
322
+ const nextMinuteInList = byMinute.find((m) => m > candidate.minute);
323
+ if (nextMinuteInList !== void 0) {
324
+ return candidate.with({ minute: nextMinuteInList, second: bySecond ? bySecond[0] : 0 });
325
+ }
326
+ candidate = candidate.with({ minute: byMinute[0], second: bySecond ? bySecond[0] : 0 }).add({ hours: 1 });
327
+ }
328
+ }
329
+ if (byHour && byHour.length > 0) {
330
+ if (!byHour.includes(candidate.hour) || candidate.hour === zdt.hour && candidate.minute < zdt.minute) {
331
+ const nextHourInList = byHour.find((h) => h > candidate.hour);
332
+ if (nextHourInList !== void 0) {
333
+ return candidate.with({
334
+ hour: nextHourInList,
335
+ minute: byMinute ? byMinute[0] : 0,
336
+ second: bySecond ? bySecond[0] : 0
337
+ });
338
+ }
339
+ candidate = candidate.with({ hour: byHour[0], minute: byMinute ? byMinute[0] : 0, second: bySecond ? bySecond[0] : 0 }).add({ days: 1 });
340
+ }
341
+ }
342
+ return candidate;
318
343
  }
319
344
  if (byMinute && byMinute.length > 1) {
320
345
  const idx = byMinute.indexOf(zdt.minute);
@@ -324,6 +349,24 @@ var RRuleTemporal = class _RRuleTemporal {
324
349
  second: bySecond ? bySecond[0] : zdt.second
325
350
  });
326
351
  }
352
+ if (freq === "MINUTELY" && idx === byMinute.length - 1) {
353
+ if (byHour && byHour.length > 0) {
354
+ const currentHourIdx = byHour.indexOf(zdt.hour);
355
+ if (currentHourIdx !== -1 && currentHourIdx < byHour.length - 1) {
356
+ return zdt.with({
357
+ hour: byHour[currentHourIdx + 1],
358
+ minute: byMinute[0],
359
+ second: bySecond ? bySecond[0] : zdt.second
360
+ });
361
+ } else {
362
+ return this.applyTimeOverride(zdt.add({ days: 1 }));
363
+ }
364
+ }
365
+ return zdt.add({ hours: interval }).with({
366
+ minute: byMinute[0],
367
+ second: bySecond ? bySecond[0] : zdt.second
368
+ });
369
+ }
327
370
  }
328
371
  if (byHour && byHour.length > 1) {
329
372
  const idx = byHour.indexOf(zdt.hour);
@@ -335,6 +378,9 @@ var RRuleTemporal = class _RRuleTemporal {
335
378
  });
336
379
  }
337
380
  }
381
+ if (freq === "HOURLY" && byHour && byHour.length > 1) {
382
+ return this.applyTimeOverride(zdt.add({ days: 1 }));
383
+ }
338
384
  return this.applyTimeOverride(this.rawAdvance(zdt));
339
385
  }
340
386
  applyTimeOverride(zdt) {
@@ -346,7 +392,7 @@ var RRuleTemporal = class _RRuleTemporal {
346
392
  return dt;
347
393
  }
348
394
  computeFirst() {
349
- var _a, _b, _c;
395
+ var _a, _b, _c, _d;
350
396
  let zdt = this.originalDtstart;
351
397
  if (((_a = this.opts.byWeekNo) == null ? void 0 : _a.length) && ["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq)) {
352
398
  let targetWeek = this.opts.byWeekNo[0];
@@ -378,15 +424,7 @@ var RRuleTemporal = class _RRuleTemporal {
378
424
  weekStart = firstThursday.subtract({ days: 3 }).add({ weeks: lastWeek + targetWeek });
379
425
  }
380
426
  if ((_b = this.opts.byDay) == null ? void 0 : _b.length) {
381
- const dayMap = {
382
- MO: 1,
383
- TU: 2,
384
- WE: 3,
385
- TH: 4,
386
- FR: 5,
387
- SA: 6,
388
- SU: 7
389
- };
427
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
390
428
  const targetDays = this.opts.byDay.map((tok) => {
391
429
  var _a2;
392
430
  return (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
@@ -413,27 +451,44 @@ var RRuleTemporal = class _RRuleTemporal {
413
451
  }
414
452
  }
415
453
  if (((_c = this.opts.byDay) == null ? void 0 : _c.length) && !this.opts.byWeekNo) {
416
- const dayMap = {
417
- MO: 1,
418
- TU: 2,
419
- WE: 3,
420
- TH: 4,
421
- FR: 5,
422
- SA: 6,
423
- SU: 7
424
- };
425
- let deltas = [];
426
- if (["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq) && this.opts.byDay.every((tok) => /^[A-Z]{2}$/.test(tok))) {
427
- deltas = this.opts.byDay.map((tok) => (dayMap[tok] - zdt.dayOfWeek + 7) % 7);
454
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
455
+ const hasOrdinalTokens = this.opts.byDay.some((tok) => /^[+-]?\d/.test(tok));
456
+ if (hasOrdinalTokens && this.opts.byMonth && (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY")) {
457
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
458
+ let foundFirst = false;
459
+ for (let year = zdt.year; year <= zdt.year + 10 && !foundFirst; year++) {
460
+ for (const month of months) {
461
+ if (year === zdt.year && month < zdt.month) continue;
462
+ const monthSample = zdt.with({ year, month, day: 1 });
463
+ const monthlyOccs = this.generateMonthlyOccurrences(monthSample);
464
+ for (const occ of monthlyOccs) {
465
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occ, zdt) >= 0) {
466
+ if (!occ.toPlainDate().equals(zdt.toPlainDate())) {
467
+ zdt = this.applyTimeOverride(occ.with({ hour: 0, minute: 0, second: 0 }));
468
+ } else {
469
+ zdt = occ;
470
+ }
471
+ foundFirst = true;
472
+ break;
473
+ }
474
+ }
475
+ if (foundFirst) break;
476
+ }
477
+ }
428
478
  } else {
429
- deltas = this.opts.byDay.map((tok) => {
430
- var _a2;
431
- const wdTok = (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
432
- return wdTok ? (dayMap[wdTok] - zdt.dayOfWeek + 7) % 7 : null;
433
- }).filter((d) => d !== null);
434
- }
435
- if (deltas.length) {
436
- zdt = zdt.add({ days: Math.min(...deltas) });
479
+ let deltas;
480
+ if (["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq) && this.opts.byDay.every((tok) => /^[A-Z]{2}$/.test(tok))) {
481
+ deltas = this.opts.byDay.map((tok) => (dayMap[tok] - zdt.dayOfWeek + 7) % 7);
482
+ } else {
483
+ deltas = this.opts.byDay.map((tok) => {
484
+ var _a2;
485
+ const wdTok = (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
486
+ return wdTok ? (dayMap[wdTok] - zdt.dayOfWeek + 7) % 7 : null;
487
+ }).filter((d) => d !== null);
488
+ }
489
+ if (deltas.length) {
490
+ zdt = zdt.add({ days: Math.min(...deltas) });
491
+ }
437
492
  }
438
493
  }
439
494
  const { byHour, byMinute, bySecond } = this.opts;
@@ -443,6 +498,18 @@ var RRuleTemporal = class _RRuleTemporal {
443
498
  ) > 0) {
444
499
  zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
445
500
  }
501
+ if (this.opts.freq === "MINUTELY" && !byMinute && import_polyfill.Temporal.ZonedDateTime.compare(
502
+ zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
503
+ this.originalDtstart
504
+ ) > 0) {
505
+ zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
506
+ }
507
+ if (this.opts.freq === "SECONDLY" && ((_d = this.opts.byWeekNo) == null ? void 0 : _d.length) && !bySecond && import_polyfill.Temporal.ZonedDateTime.compare(
508
+ zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
509
+ this.originalDtstart
510
+ ) > 0) {
511
+ zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
512
+ }
446
513
  if (byHour || byMinute || bySecond) {
447
514
  const candidates = this.expandByTime(zdt);
448
515
  for (const candidate of candidates) {
@@ -459,15 +526,7 @@ var RRuleTemporal = class _RRuleTemporal {
459
526
  matchesByDay(zdt) {
460
527
  const { byDay, freq } = this.opts;
461
528
  if (!byDay) return true;
462
- const dayMap = {
463
- MO: 1,
464
- TU: 2,
465
- WE: 3,
466
- TH: 4,
467
- FR: 5,
468
- SA: 6,
469
- SU: 7
470
- };
529
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
471
530
  for (const token of byDay) {
472
531
  const m = token.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
473
532
  if (!m) continue;
@@ -500,26 +559,57 @@ var RRuleTemporal = class _RRuleTemporal {
500
559
  if (!byMonth) return true;
501
560
  return byMonth.includes(zdt.month);
502
561
  }
562
+ matchesNumericConstraint(value, constraints, maxPositiveValue) {
563
+ return constraints.some((c) => {
564
+ const target = c > 0 ? c : maxPositiveValue + c + 1;
565
+ return value === target;
566
+ });
567
+ }
503
568
  matchesByMonthDay(zdt) {
504
569
  const { byMonthDay } = this.opts;
505
570
  if (!byMonthDay) return true;
506
571
  const lastDay = zdt.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
507
- return byMonthDay.some((d) => d > 0 ? zdt.day === d : zdt.day === lastDay + d + 1);
572
+ return this.matchesNumericConstraint(zdt.day, byMonthDay, lastDay);
573
+ }
574
+ matchesByHour(zdt) {
575
+ const { byHour } = this.opts;
576
+ if (!byHour) return true;
577
+ if (byHour.includes(zdt.hour)) {
578
+ return true;
579
+ }
580
+ for (const h of byHour) {
581
+ const intendedTime = zdt.with({ hour: h });
582
+ if (intendedTime.hour === zdt.hour) {
583
+ return true;
584
+ }
585
+ }
586
+ return false;
587
+ }
588
+ matchesByMinute(zdt) {
589
+ const { byMinute } = this.opts;
590
+ if (!byMinute) return true;
591
+ return byMinute.includes(zdt.minute);
592
+ }
593
+ matchesBySecond(zdt) {
594
+ const { bySecond } = this.opts;
595
+ if (!bySecond) return true;
596
+ return bySecond.includes(zdt.second);
508
597
  }
509
598
  matchesAll(zdt) {
510
- return this.matchesByDay(zdt) && this.matchesByMonth(zdt) && this.matchesByMonthDay(zdt) && this.matchesByYearDay(zdt) && this.matchesByWeekNo(zdt);
599
+ return this.matchesByMonth(zdt) && this.matchesByWeekNo(zdt) && this.matchesByYearDay(zdt) && this.matchesByMonthDay(zdt) && this.matchesByDay(zdt) && this.matchesByHour(zdt) && this.matchesByMinute(zdt) && this.matchesBySecond(zdt);
511
600
  }
512
601
  matchesByYearDay(zdt) {
513
602
  const { byYearDay } = this.opts;
514
603
  if (!byYearDay) return true;
515
604
  const dayOfYear = zdt.dayOfYear;
516
605
  const last = zdt.with({ month: 12, day: 31 }).dayOfYear;
517
- return byYearDay.some((d) => d > 0 ? dayOfYear === d : dayOfYear === last + d + 1);
606
+ return this.matchesNumericConstraint(dayOfYear, byYearDay, last);
518
607
  }
519
608
  getIsoWeekInfo(zdt) {
520
609
  const thursday = zdt.add({ days: 4 - zdt.dayOfWeek });
521
610
  const year = thursday.year;
522
- const firstThursday = thursday.with({ month: 1, day: 1 }).add({ days: (4 - thursday.with({ month: 1, day: 1 }).dayOfWeek + 7) % 7 });
611
+ const jan1 = zdt.with({ year, month: 1, day: 1 });
612
+ const firstThursday = jan1.add({ days: (4 - jan1.dayOfWeek + 7) % 7 });
523
613
  const diffDays = thursday.toPlainDate().since(firstThursday.toPlainDate()).days;
524
614
  const week = Math.floor(diffDays / 7) + 1;
525
615
  return { week, year };
@@ -529,11 +619,8 @@ var RRuleTemporal = class _RRuleTemporal {
529
619
  if (!byWeekNo) return true;
530
620
  const { week, year } = this.getIsoWeekInfo(zdt);
531
621
  const jan1 = zdt.with({ year, month: 1, day: 1 });
532
- const dec31 = zdt.with({ year, month: 12, day: 31 });
533
- let lastWeek = 52;
534
- if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
535
- lastWeek = 53;
536
- }
622
+ const isLeapYear = jan1.inLeapYear;
623
+ const lastWeek = jan1.dayOfWeek === 4 || isLeapYear && jan1.dayOfWeek === 3 ? 53 : 52;
537
624
  return byWeekNo.some((wn) => {
538
625
  if (wn > 0) {
539
626
  return week === wn;
@@ -545,470 +632,498 @@ var RRuleTemporal = class _RRuleTemporal {
545
632
  options() {
546
633
  return this.opts;
547
634
  }
635
+ addDtstartIfNeeded(dates, iterator) {
636
+ if (this.includeDtstart && !this.matchesAll(this.originalDtstart)) {
637
+ if (iterator && !iterator(this.originalDtstart, dates.length)) {
638
+ return false;
639
+ }
640
+ dates.push(this.originalDtstart);
641
+ if (this.shouldBreakForCountLimit(dates.length)) {
642
+ return false;
643
+ }
644
+ }
645
+ return true;
646
+ }
647
+ processOccurrences(occs, dates, start, iterator, extraFilters) {
648
+ let shouldBreak = false;
649
+ for (const occ of occs) {
650
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
651
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
652
+ shouldBreak = true;
653
+ break;
654
+ }
655
+ if (extraFilters && !extraFilters(occ)) {
656
+ continue;
657
+ }
658
+ if (iterator && !iterator(occ, dates.length)) {
659
+ shouldBreak = true;
660
+ break;
661
+ }
662
+ dates.push(occ);
663
+ if (this.shouldBreakForCountLimit(dates.length)) {
664
+ shouldBreak = true;
665
+ break;
666
+ }
667
+ }
668
+ return { shouldBreak };
669
+ }
548
670
  /**
549
671
  * Returns all occurrences of the rule.
550
672
  * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
551
673
  * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
552
674
  */
553
- all(iterator) {
554
- var _a;
555
- if (!this.opts.count && !this.opts.until && !iterator) {
556
- throw new Error("all() requires iterator when no COUNT/UNTIL");
557
- }
675
+ _allMonthlyByDayOrMonthDay(iterator) {
558
676
  const dates = [];
559
677
  let iterationCount = 0;
560
- if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
561
- const start = this.originalDtstart;
562
- let monthCursor = start.with({ day: 1 });
563
- let matchCount = 0;
564
- if (this.includeDtstart && !this.matchesAll(start)) {
565
- if (iterator && !iterator(start, matchCount)) {
566
- return this.applyCountLimitAndMergeRDates(dates, iterator);
567
- }
568
- dates.push(start);
569
- matchCount++;
570
- if (this.shouldBreakForCountLimit(matchCount)) {
571
- return this.applyCountLimitAndMergeRDates(dates, iterator);
572
- }
678
+ const start = this.originalDtstart;
679
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
680
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
681
+ }
682
+ let monthCursor = start.with({ day: 1 });
683
+ while (true) {
684
+ if (++iterationCount > this.maxIterations) {
685
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
573
686
  }
574
- outer_month: while (true) {
575
- if (++iterationCount > this.maxIterations) {
576
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
577
- }
578
- let occs = this.generateMonthlyOccurrences(monthCursor);
579
- occs = this.applyBySetPos(occs);
580
- if (monthCursor.month === start.month && occs.some((o) => import_polyfill.Temporal.ZonedDateTime.compare(o, start) < 0) && occs.some((o) => import_polyfill.Temporal.ZonedDateTime.compare(o, start) === 0)) {
581
- monthCursor = monthCursor.add({ months: this.opts.interval });
582
- continue outer_month;
583
- }
584
- for (const occ of occs) {
585
- if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
586
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
587
- break outer_month;
588
- }
589
- if (iterator && !iterator(occ, matchCount)) {
590
- break outer_month;
591
- }
592
- dates.push(occ);
593
- matchCount++;
594
- if (this.shouldBreakForCountLimit(matchCount)) {
595
- break outer_month;
596
- }
597
- }
687
+ let occs = this.generateMonthlyOccurrences(monthCursor);
688
+ occs = this.applyBySetPos(occs);
689
+ if (monthCursor.month === start.month && occs.some((o) => import_polyfill.Temporal.ZonedDateTime.compare(o, start) < 0) && occs.some((o) => import_polyfill.Temporal.ZonedDateTime.compare(o, start) === 0)) {
598
690
  monthCursor = monthCursor.add({ months: this.opts.interval });
691
+ continue;
599
692
  }
693
+ const { shouldBreak } = this.processOccurrences(occs, dates, start, iterator);
694
+ if (shouldBreak) {
695
+ break;
696
+ }
697
+ monthCursor = monthCursor.add({ months: this.opts.interval });
698
+ }
699
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
700
+ }
701
+ _allWeekly(iterator) {
702
+ var _a;
703
+ const dates = [];
704
+ let iterationCount = 0;
705
+ const start = this.originalDtstart;
706
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
600
707
  return this.applyCountLimitAndMergeRDates(dates, iterator);
601
708
  }
602
- if (this.opts.freq === "WEEKLY") {
603
- if (this.opts.byYearDay && this.opts.byYearDay.length > 0) {
604
- const start2 = this.originalDtstart;
605
- if (this.includeDtstart && !this.matchesAll(start2)) {
606
- if (iterator && !iterator(start2, 0)) {
607
- return this.applyCountLimitAndMergeRDates(dates, iterator);
608
- }
609
- dates.push(start2);
610
- if (this.shouldBreakForCountLimit(1)) {
611
- return this.applyCountLimitAndMergeRDates(dates, iterator);
612
- }
613
- }
614
- let yearCursor = start2.with({ month: 1, day: 1 });
615
- let matchCount2 = dates.length;
616
- outer_year_for_weekly: while (true) {
617
- if (++iterationCount > this.maxIterations) {
618
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
619
- }
620
- const occs = this.generateYearlyOccurrences(yearCursor);
621
- for (const occ of occs) {
622
- if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start2) < 0) continue;
623
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
624
- break outer_year_for_weekly;
625
- }
626
- if (iterator && !iterator(occ, matchCount2)) {
627
- break outer_year_for_weekly;
628
- }
629
- dates.push(occ);
630
- matchCount2++;
631
- if (this.shouldBreakForCountLimit(matchCount2)) {
632
- break outer_year_for_weekly;
633
- }
634
- }
635
- if (this.opts.until && yearCursor.year > this.opts.until.year) {
636
- break;
637
- }
638
- yearCursor = yearCursor.add({ years: 1 });
639
- }
640
- return this.applyCountLimitAndMergeRDates(dates, iterator);
641
- }
642
- const start = this.originalDtstart;
643
- if (this.includeDtstart && !this.matchesAll(start)) {
644
- if (iterator && !iterator(start, 0)) {
645
- return this.applyCountLimitAndMergeRDates(dates, iterator);
646
- }
647
- dates.push(start);
648
- if (this.shouldBreakForCountLimit(1)) {
649
- return this.applyCountLimitAndMergeRDates(dates, iterator);
650
- }
709
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
710
+ const tokens = this.opts.byDay ? [...this.opts.byDay] : this.opts.byMonthDay && this.opts.byMonthDay.length > 0 ? Object.keys(dayMap) : [Object.entries(dayMap).find(([, d]) => d === start.dayOfWeek)[0]];
711
+ const dows = tokens.map((tok) => dayMap[tok.slice(-2)]).filter((d) => d !== void 0).sort((a, b) => a - b);
712
+ const firstWeekDates = dows.map((dw) => {
713
+ const delta = (dw - start.dayOfWeek + 7) % 7;
714
+ return start.add({ days: delta });
715
+ });
716
+ const firstOccurrence = firstWeekDates.reduce((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b) <= 0 ? a : b);
717
+ const wkstDay = (_a = dayMap[this.opts.wkst || "MO"]) != null ? _a : 1;
718
+ const firstOccWeekOffset = (firstOccurrence.dayOfWeek - wkstDay + 7) % 7;
719
+ let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
720
+ while (true) {
721
+ if (++iterationCount > this.maxIterations) {
722
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
651
723
  }
652
- const dayMap = {
653
- MO: 1,
654
- TU: 2,
655
- WE: 3,
656
- TH: 4,
657
- FR: 5,
658
- SA: 6,
659
- SU: 7
660
- };
661
- const tokens = this.opts.byDay ? [...this.opts.byDay] : this.opts.byMonthDay && this.opts.byMonthDay.length > 0 ? Object.keys(dayMap) : [Object.entries(dayMap).find(([, d]) => d === start.dayOfWeek)[0]];
662
- const dows = tokens.map((tok) => dayMap[tok.slice(-2)]).filter((d) => d !== void 0).sort((a, b) => a - b);
663
- const firstWeekDates = dows.map((dw) => {
664
- const delta = (dw - start.dayOfWeek + 7) % 7;
665
- return start.add({ days: delta });
666
- });
667
- let firstOccurrence = firstWeekDates.reduce((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b) <= 0 ? a : b);
668
- const wkstDay = (_a = dayMap[this.opts.wkst || "MO"]) != null ? _a : 1;
669
- const firstOccWeekOffset = (firstOccurrence.dayOfWeek - wkstDay + 7) % 7;
670
- let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
671
- let matchCount = 0;
672
- outer_week: while (true) {
673
- if (++iterationCount > this.maxIterations) {
674
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
675
- }
676
- let occs = dows.flatMap((dw) => {
677
- const delta = (dw - wkstDay + 7) % 7;
678
- const sameDate = weekCursor.add({ days: delta });
679
- return this.expandByTime(sameDate);
680
- }).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
681
- occs = this.applyBySetPos(occs);
682
- for (const occ of occs) {
683
- if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
684
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
685
- break outer_week;
686
- }
687
- if (!this.matchesByMonth(occ)) {
688
- continue;
689
- }
690
- if (!this.matchesByMonthDay(occ)) {
691
- continue;
692
- }
693
- if (iterator && !iterator(occ, matchCount)) {
694
- break outer_week;
695
- }
696
- dates.push(occ);
697
- matchCount++;
698
- if (this.shouldBreakForCountLimit(matchCount)) {
699
- break outer_week;
700
- }
701
- }
702
- weekCursor = weekCursor.add({ weeks: this.opts.interval });
724
+ let occs = dows.flatMap((dw) => {
725
+ const delta = (dw - wkstDay + 7) % 7;
726
+ const sameDate = weekCursor.add({ days: delta });
727
+ return this.expandByTime(sameDate);
728
+ }).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
729
+ occs = this.applyBySetPos(occs);
730
+ const { shouldBreak } = this.processOccurrences(
731
+ occs,
732
+ dates,
733
+ start,
734
+ iterator,
735
+ (occ) => this.matchesByMonth(occ) && this.matchesByMonthDay(occ)
736
+ );
737
+ if (shouldBreak) {
738
+ break;
703
739
  }
740
+ weekCursor = weekCursor.add({ weeks: this.opts.interval });
741
+ }
742
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
743
+ }
744
+ _allMonthlyByMonth(iterator) {
745
+ const dates = [];
746
+ let iterationCount = 0;
747
+ const start = this.originalDtstart;
748
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
704
749
  return this.applyCountLimitAndMergeRDates(dates, iterator);
705
750
  }
706
- if (this.opts.freq === "MONTHLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay) {
707
- const start = this.originalDtstart;
708
- if (this.includeDtstart && !this.matchesAll(start)) {
709
- if (iterator && !iterator(start, 0)) {
710
- return this.applyCountLimitAndMergeRDates(dates, iterator);
711
- }
712
- dates.push(start);
713
- if (this.shouldBreakForCountLimit(1)) {
714
- return this.applyCountLimitAndMergeRDates(dates, iterator);
715
- }
751
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
752
+ let monthOffset = 0;
753
+ let startMonthIndex = months.findIndex((m) => m >= start.month);
754
+ if (startMonthIndex === -1) {
755
+ startMonthIndex = 0;
756
+ monthOffset = 1;
757
+ }
758
+ while (true) {
759
+ if (++iterationCount > this.maxIterations) {
760
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
716
761
  }
717
- const months = [...this.opts.byMonth].sort((a, b) => a - b);
718
- let monthOffset = 0;
719
- let matchCount = dates.length;
720
- let startMonthIndex = months.findIndex((m) => m >= start.month);
721
- if (startMonthIndex === -1) {
722
- startMonthIndex = 0;
723
- monthOffset = 1;
724
- }
725
- while (true) {
726
- if (++iterationCount > this.maxIterations) {
727
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
728
- }
729
- const monthIndex = startMonthIndex + monthOffset;
730
- const targetMonth = months[monthIndex % months.length];
731
- const yearsToAdd = Math.floor(monthIndex / months.length);
732
- const candidate = start.with({
733
- year: start.year + yearsToAdd,
734
- month: targetMonth
735
- });
736
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(candidate, this.opts.until) > 0) {
762
+ const monthIndex = startMonthIndex + monthOffset;
763
+ const targetMonth = months[monthIndex % months.length];
764
+ const yearsToAdd = Math.floor(monthIndex / months.length);
765
+ const candidate = start.with({
766
+ year: start.year + yearsToAdd,
767
+ month: targetMonth
768
+ });
769
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(candidate, this.opts.until) > 0) {
770
+ break;
771
+ }
772
+ if (import_polyfill.Temporal.ZonedDateTime.compare(candidate, start) >= 0) {
773
+ if (iterator && !iterator(candidate, dates.length)) {
737
774
  break;
738
775
  }
739
- if (import_polyfill.Temporal.ZonedDateTime.compare(candidate, start) >= 0) {
740
- if (iterator && !iterator(candidate, matchCount)) {
741
- break;
742
- }
743
- dates.push(candidate);
744
- matchCount++;
745
- if (this.shouldBreakForCountLimit(matchCount)) {
746
- break;
747
- }
776
+ dates.push(candidate);
777
+ if (this.shouldBreakForCountLimit(dates.length)) {
778
+ break;
748
779
  }
749
- monthOffset++;
750
780
  }
781
+ monthOffset++;
782
+ }
783
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
784
+ }
785
+ _allYearlyByMonth(iterator) {
786
+ const dates = [];
787
+ let iterationCount = 0;
788
+ const start = this.originalDtstart;
789
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
751
790
  return this.applyCountLimitAndMergeRDates(dates, iterator);
752
791
  }
753
- if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay && !this.opts.byWeekNo) {
754
- const start = this.originalDtstart;
755
- if (this.includeDtstart && !this.matchesAll(start)) {
756
- if (iterator && !iterator(start, 0)) {
757
- return this.applyCountLimitAndMergeRDates(dates, iterator);
792
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
793
+ let yearOffset = 0;
794
+ while (true) {
795
+ if (++iterationCount > this.maxIterations) {
796
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
797
+ }
798
+ const year = start.year + yearOffset * this.opts.interval;
799
+ for (const month of months) {
800
+ let occ = start.with({ year, month });
801
+ occ = this.applyTimeOverride(occ);
802
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) {
803
+ continue;
758
804
  }
759
- dates.push(start);
760
- if (this.shouldBreakForCountLimit(1)) {
805
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
761
806
  return this.applyCountLimitAndMergeRDates(dates, iterator);
762
807
  }
763
- }
764
- const months = [...this.opts.byMonth].sort((a, b) => a - b);
765
- let yearOffset = 0;
766
- let matchCount = 0;
767
- while (true) {
768
- if (++iterationCount > this.maxIterations) {
769
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
808
+ if (iterator && !iterator(occ, dates.length)) {
809
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
770
810
  }
771
- const year = start.year + yearOffset * this.opts.interval;
772
- for (const month of months) {
773
- let occ = start.with({ year, month });
774
- occ = this.applyTimeOverride(occ);
775
- if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) {
776
- continue;
777
- }
778
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
779
- return dates;
780
- }
781
- if (iterator && !iterator(occ, matchCount)) {
782
- return dates;
783
- }
784
- dates.push(occ);
785
- matchCount++;
786
- if (this.shouldBreakForCountLimit(matchCount)) {
787
- return this.applyCountLimitAndMergeRDates(dates, iterator);
788
- }
811
+ dates.push(occ);
812
+ if (this.shouldBreakForCountLimit(dates.length)) {
813
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
789
814
  }
790
- yearOffset++;
791
815
  }
816
+ yearOffset++;
817
+ }
818
+ }
819
+ _allYearlyComplex(iterator) {
820
+ const dates = [];
821
+ let iterationCount = 0;
822
+ const start = this.originalDtstart;
823
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
792
824
  return this.applyCountLimitAndMergeRDates(dates, iterator);
793
825
  }
794
- if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
795
- const start = this.originalDtstart;
796
- if (this.includeDtstart && !this.matchesAll(start)) {
797
- if (iterator && !iterator(start, 0)) {
798
- return this.applyCountLimitAndMergeRDates(dates, iterator);
799
- }
800
- dates.push(start);
801
- if (this.shouldBreakForCountLimit(1)) {
802
- return this.applyCountLimitAndMergeRDates(dates, iterator);
803
- }
826
+ let yearCursor = start.with({ month: 1, day: 1 });
827
+ while (true) {
828
+ if (++iterationCount > this.maxIterations) {
829
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
804
830
  }
805
- let yearCursor = start.with({ month: 1, day: 1 });
806
- let matchCount = 0;
807
- outer_year: while (true) {
808
- if (++iterationCount > this.maxIterations) {
809
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
810
- }
811
- const occs = this.generateYearlyOccurrences(yearCursor);
812
- for (const occ of occs) {
813
- if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
814
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
815
- break outer_year;
816
- }
817
- if (iterator && !iterator(occ, matchCount)) {
818
- break outer_year;
819
- }
820
- dates.push(occ);
821
- matchCount++;
822
- if (this.shouldBreakForCountLimit(matchCount)) {
823
- break outer_year;
831
+ const occs = this.generateYearlyOccurrences(yearCursor);
832
+ const uniqueOccs = [];
833
+ if (occs.length > 0) {
834
+ uniqueOccs.push(occs[0]);
835
+ for (let i = 1; i < occs.length; i++) {
836
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occs[i], occs[i - 1]) !== 0) {
837
+ uniqueOccs.push(occs[i]);
824
838
  }
825
839
  }
826
- yearCursor = yearCursor.add({ years: this.opts.interval });
827
840
  }
841
+ const { shouldBreak } = this.processOccurrences(uniqueOccs, dates, start, iterator);
842
+ if (shouldBreak) {
843
+ break;
844
+ }
845
+ const interval = this.opts.freq === "WEEKLY" ? 1 : this.opts.interval;
846
+ yearCursor = yearCursor.add({ years: interval });
847
+ if (this.opts.freq === "WEEKLY" && this.opts.until && yearCursor.year > this.opts.until.year) {
848
+ break;
849
+ }
850
+ }
851
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
852
+ }
853
+ _allMinutelySecondlyComplex(iterator) {
854
+ const dates = [];
855
+ let iterationCount = 0;
856
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
828
857
  return this.applyCountLimitAndMergeRDates(dates, iterator);
829
858
  }
830
- if (this.opts.freq === "YEARLY" && (this.opts.byYearDay || this.opts.byWeekNo)) {
831
- const start = this.originalDtstart;
832
- if (this.includeDtstart && !this.matchesAll(start)) {
833
- if (iterator && !iterator(start, 0)) {
834
- return this.applyCountLimitAndMergeRDates(dates, iterator);
835
- }
836
- dates.push(start);
837
- if (this.shouldBreakForCountLimit(1)) {
838
- return this.applyCountLimitAndMergeRDates(dates, iterator);
839
- }
859
+ let current = this.computeFirst();
860
+ while (true) {
861
+ if (++iterationCount > this.maxIterations) {
862
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
863
+ }
864
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
865
+ break;
840
866
  }
841
- let yearCursor = start.with({ month: 1, day: 1 });
842
- let matchCount = 0;
843
- outer_year2: while (true) {
844
- if (++iterationCount > this.maxIterations) {
845
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
867
+ if (this.matchesAll(current)) {
868
+ if (iterator && !iterator(current, dates.length)) {
869
+ break;
846
870
  }
847
- const occs = this.generateYearlyOccurrences(yearCursor);
848
- for (const occ of occs) {
849
- if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
850
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
851
- break outer_year2;
852
- }
853
- if (iterator && !iterator(occ, matchCount)) {
854
- break outer_year2;
855
- }
856
- dates.push(occ);
857
- matchCount++;
858
- if (this.shouldBreakForCountLimit(matchCount)) {
859
- break outer_year2;
860
- }
871
+ dates.push(current);
872
+ if (this.shouldBreakForCountLimit(dates.length)) {
873
+ break;
861
874
  }
862
- yearCursor = yearCursor.add({ years: this.opts.interval });
875
+ current = this.nextCandidateSameDate(current);
876
+ } else {
877
+ current = this.findNextValidDate(current);
863
878
  }
879
+ }
880
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
881
+ }
882
+ _allMonthlyByWeekNo(iterator) {
883
+ const dates = [];
884
+ let iterationCount = 0;
885
+ const start = this.originalDtstart;
886
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
864
887
  return this.applyCountLimitAndMergeRDates(dates, iterator);
865
888
  }
866
- if (this.opts.freq === "MONTHLY" && this.opts.byYearDay && this.opts.byYearDay.length > 0 && !this.opts.byDay && !this.opts.byMonthDay) {
867
- const start = this.originalDtstart;
868
- let matchCount = 0;
869
- if (this.includeDtstart && !this.matchesAll(start)) {
870
- if (iterator && !iterator(start, matchCount)) {
871
- return this.applyCountLimitAndMergeRDates(dates, iterator);
872
- }
873
- dates.push(start);
874
- matchCount++;
875
- if (this.shouldBreakForCountLimit(matchCount)) {
876
- return this.applyCountLimitAndMergeRDates(dates, iterator);
877
- }
889
+ let current = start;
890
+ const weekNos = [...this.opts.byWeekNo].sort((a, b) => a - b);
891
+ const interval = this.opts.interval;
892
+ let monthsAdvanced = 0;
893
+ let lastYearProcessed = -1;
894
+ outer_loop: while (true) {
895
+ if (this.shouldBreakForCountLimit(dates.length)) {
896
+ break;
878
897
  }
879
- let year = start.year;
880
- const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
881
- const interval = this.opts.interval;
882
- const startMonthAbs = start.year * 12 + start.month;
883
- outer_loop: while (true) {
884
- if (this.shouldBreakForCountLimit(matchCount)) {
885
- break;
886
- }
887
- if (++iterationCount > this.maxIterations) {
888
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
889
- }
890
- const yearStart = start.with({ year, month: 1, day: 1 });
891
- const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
892
- for (const yd of yearDays) {
893
- const dayNum = yd > 0 ? yd : lastDayOfYear + yd + 1;
894
- if (dayNum <= 0 || dayNum > lastDayOfYear) continue;
895
- const baseOcc = yearStart.add({ days: dayNum - 1 });
896
- for (const occ of this.expandByTime(baseOcc)) {
897
- if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
898
- if (dates.some((d) => import_polyfill.Temporal.ZonedDateTime.compare(d, occ) === 0)) continue;
899
- const occMonthAbs = occ.year * 12 + occ.month;
900
- if ((occMonthAbs - startMonthAbs) % interval !== 0) {
901
- continue;
902
- }
903
- if (!this.matchesByMonth(occ)) {
904
- continue;
905
- }
906
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
907
- break outer_loop;
908
- }
909
- if (iterator && !iterator(occ, matchCount)) {
910
- break outer_loop;
911
- }
912
- dates.push(occ);
913
- matchCount++;
914
- if (this.shouldBreakForCountLimit(matchCount)) {
915
- break outer_loop;
898
+ if (++iterationCount > this.maxIterations) {
899
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
900
+ }
901
+ const year = current.year;
902
+ if (year !== lastYearProcessed && current.month >= start.month) {
903
+ lastYearProcessed = year;
904
+ for (const weekNo of weekNos) {
905
+ const occs = this.generateOccurrencesForWeekInYear(year, weekNo);
906
+ for (const occ of occs) {
907
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) >= 0) {
908
+ if (iterator && !iterator(occ, dates.length)) {
909
+ break outer_loop;
910
+ }
911
+ dates.push(occ);
912
+ if (this.shouldBreakForCountLimit(dates.length)) {
913
+ break outer_loop;
914
+ }
916
915
  }
917
916
  }
918
917
  }
919
- year++;
920
- if (this.opts.until && year > this.opts.until.year + 2) {
921
- break;
922
- }
923
- if (!this.opts.until && this.opts.count) {
924
- const yearsToScan = Math.ceil(this.opts.count / (this.opts.byYearDay.length || 1)) * interval + 5;
925
- if (year > start.year + yearsToScan) {
926
- break;
927
- }
928
- }
929
918
  }
919
+ monthsAdvanced += interval;
920
+ current = start.add({ months: monthsAdvanced });
921
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
922
+ break;
923
+ }
924
+ }
925
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
926
+ }
927
+ _allMonthlyByYearDay(iterator) {
928
+ const dates = [];
929
+ let iterationCount = 0;
930
+ const start = this.originalDtstart;
931
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
930
932
  return this.applyCountLimitAndMergeRDates(dates, iterator);
931
933
  }
932
- if (this.opts.freq === "DAILY" && this.opts.bySetPos) {
933
- let start = this.originalDtstart;
934
- let matchCount = 0;
935
- if (this.includeDtstart && !this.matchesAll(start)) {
936
- if (iterator && !iterator(start, matchCount)) {
937
- return this.applyCountLimitAndMergeRDates(dates, iterator);
938
- }
939
- dates.push(start);
940
- matchCount++;
941
- if (this.shouldBreakForCountLimit(matchCount)) {
942
- return this.applyCountLimitAndMergeRDates(dates, iterator);
943
- }
934
+ let year = start.year;
935
+ const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
936
+ const interval = this.opts.interval;
937
+ const startMonthAbs = start.year * 12 + start.month;
938
+ outer_loop: while (true) {
939
+ if (this.shouldBreakForCountLimit(dates.length)) {
940
+ break;
944
941
  }
945
- let dayCursor = start.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
946
- outer_daily: while (true) {
947
- if (++iterationCount > this.maxIterations) {
948
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
949
- }
950
- let dayOccs = this.expandByTime(dayCursor);
951
- dayOccs = dayOccs.filter((occ) => this.matchesAll(occ));
952
- dayOccs = this.applyBySetPos(dayOccs);
953
- for (const occ of dayOccs) {
942
+ if (++iterationCount > this.maxIterations) {
943
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
944
+ }
945
+ const yearStart = start.with({ year, month: 1, day: 1 });
946
+ const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
947
+ for (const yd of yearDays) {
948
+ const dayNum = yd > 0 ? yd : lastDayOfYear + yd + 1;
949
+ if (dayNum <= 0 || dayNum > lastDayOfYear) continue;
950
+ const baseOcc = yearStart.add({ days: dayNum - 1 });
951
+ for (const occ of this.expandByTime(baseOcc)) {
954
952
  if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
953
+ if (dates.some((d) => import_polyfill.Temporal.ZonedDateTime.compare(d, occ) === 0)) continue;
954
+ const occMonthAbs = occ.year * 12 + occ.month;
955
+ if ((occMonthAbs - startMonthAbs) % interval !== 0) {
956
+ continue;
957
+ }
958
+ if (!this.matchesByMonth(occ)) {
959
+ continue;
960
+ }
955
961
  if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
956
- break outer_daily;
962
+ break outer_loop;
957
963
  }
958
- if (iterator && !iterator(occ, matchCount)) {
959
- break outer_daily;
964
+ if (iterator && !iterator(occ, dates.length)) {
965
+ break outer_loop;
960
966
  }
961
967
  dates.push(occ);
962
- matchCount++;
963
- if (this.shouldBreakForCountLimit(matchCount)) {
964
- break outer_daily;
968
+ if (this.shouldBreakForCountLimit(dates.length)) {
969
+ break outer_loop;
965
970
  }
966
971
  }
967
- dayCursor = dayCursor.add({ days: this.opts.interval });
968
972
  }
969
- } else {
970
- let current = this.computeFirst();
971
- let matchCount = 0;
972
- if (this.includeDtstart && import_polyfill.Temporal.ZonedDateTime.compare(current, this.originalDtstart) > 0) {
973
- if (iterator && !iterator(this.originalDtstart, matchCount)) {
974
- return this.applyCountLimitAndMergeRDates(dates, iterator);
975
- }
976
- dates.push(this.originalDtstart);
977
- matchCount++;
978
- if (this.shouldBreakForCountLimit(matchCount)) {
979
- return this.applyCountLimitAndMergeRDates(dates, iterator);
980
- }
973
+ year++;
974
+ if (this.opts.until && year > this.opts.until.year + 2) {
975
+ break;
981
976
  }
982
- while (true) {
983
- if (++iterationCount > this.maxIterations) {
984
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
977
+ if (!this.opts.until && this.opts.count) {
978
+ const yearsToScan = Math.ceil(this.opts.count / (this.opts.byYearDay.length || 1)) * interval + 5;
979
+ if (year > start.year + yearsToScan) {
980
+ break;
985
981
  }
986
- if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
982
+ }
983
+ }
984
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
985
+ }
986
+ _allDailyMinutelyHourlyWithBySetPos(iterator) {
987
+ const dates = [];
988
+ let iterationCount = 0;
989
+ const start = this.originalDtstart;
990
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
991
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
992
+ }
993
+ let cursor;
994
+ let duration;
995
+ switch (this.opts.freq) {
996
+ case "MINUTELY":
997
+ cursor = start.with({ second: 0, microsecond: 0, nanosecond: 0 });
998
+ duration = { minutes: this.opts.interval };
999
+ break;
1000
+ case "HOURLY":
1001
+ cursor = start.with({ minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
1002
+ duration = { hours: this.opts.interval };
1003
+ break;
1004
+ case "DAILY":
1005
+ cursor = start.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
1006
+ duration = { days: this.opts.interval };
1007
+ break;
1008
+ default:
1009
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1010
+ }
1011
+ while (true) {
1012
+ if (++iterationCount > this.maxIterations) {
1013
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1014
+ }
1015
+ let periodOccs = this.expandByTime(cursor);
1016
+ periodOccs = periodOccs.filter((occ) => this.matchesAll(occ));
1017
+ periodOccs = this.applyBySetPos(periodOccs);
1018
+ const { shouldBreak } = this.processOccurrences(periodOccs, dates, start, iterator);
1019
+ if (shouldBreak) {
1020
+ break;
1021
+ }
1022
+ cursor = cursor.add(duration);
1023
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(cursor, this.opts.until) > 0) {
1024
+ break;
1025
+ }
1026
+ }
1027
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1028
+ }
1029
+ _allFallback(iterator) {
1030
+ const dates = [];
1031
+ let iterationCount = 0;
1032
+ let current = this.computeFirst();
1033
+ if (this.includeDtstart && import_polyfill.Temporal.ZonedDateTime.compare(current, this.originalDtstart) > 0) {
1034
+ if (iterator && !iterator(this.originalDtstart, dates.length)) {
1035
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1036
+ }
1037
+ dates.push(this.originalDtstart);
1038
+ if (this.shouldBreakForCountLimit(dates.length)) {
1039
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1040
+ }
1041
+ }
1042
+ while (true) {
1043
+ if (++iterationCount > this.maxIterations) {
1044
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1045
+ }
1046
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
1047
+ break;
1048
+ }
1049
+ if (this.matchesAll(current)) {
1050
+ if (iterator && !iterator(current, dates.length)) {
987
1051
  break;
988
1052
  }
989
- if (this.matchesAll(current)) {
990
- if (iterator && !iterator(current, matchCount)) {
991
- break;
992
- }
993
- dates.push(current);
994
- matchCount++;
995
- if (this.shouldBreakForCountLimit(matchCount)) {
996
- break;
997
- }
1053
+ dates.push(current);
1054
+ if (this.shouldBreakForCountLimit(dates.length)) {
1055
+ break;
998
1056
  }
999
- current = this.nextCandidateSameDate(current);
1000
1057
  }
1058
+ current = this.nextCandidateSameDate(current);
1001
1059
  }
1002
1060
  return this.applyCountLimitAndMergeRDates(dates, iterator);
1003
1061
  }
1062
+ /**
1063
+ * Returns all occurrences of the rule.
1064
+ * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
1065
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
1066
+ */
1067
+ all(iterator) {
1068
+ if (this.opts.byWeekNo && this.opts.byYearDay) {
1069
+ const yearStart = this.originalDtstart.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 });
1070
+ const yearDays = this.opts.byYearDay.map((yd) => {
1071
+ const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
1072
+ return yd > 0 ? yd : lastDayOfYear + yd + 1;
1073
+ });
1074
+ let possibleDate = false;
1075
+ for (const yd of yearDays) {
1076
+ const date = yearStart.add({ days: yd - 1 });
1077
+ if (this.matchesByWeekNo(date)) {
1078
+ possibleDate = true;
1079
+ break;
1080
+ }
1081
+ }
1082
+ if (!possibleDate) {
1083
+ return [];
1084
+ }
1085
+ }
1086
+ if (!this.opts.count && !this.opts.until && !iterator) {
1087
+ throw new Error("all() requires iterator when no COUNT/UNTIL");
1088
+ }
1089
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay) && !this.opts.byWeekNo) {
1090
+ return this._allMonthlyByDayOrMonthDay(iterator);
1091
+ }
1092
+ if (this.opts.freq === "WEEKLY" && !(this.opts.byYearDay && this.opts.byYearDay.length > 0) && !(this.opts.byWeekNo && this.opts.byWeekNo.length > 0)) {
1093
+ return this._allWeekly(iterator);
1094
+ }
1095
+ if (this.opts.freq === "MONTHLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay) {
1096
+ return this._allMonthlyByMonth(iterator);
1097
+ }
1098
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay && !this.opts.byWeekNo) {
1099
+ return this._allYearlyByMonth(iterator);
1100
+ }
1101
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay || this.opts.byYearDay || this.opts.byWeekNo) || this.opts.freq === "WEEKLY" && this.opts.byYearDay && this.opts.byYearDay.length > 0 || this.opts.freq === "WEEKLY" && this.opts.byWeekNo && this.opts.byWeekNo.length > 0) {
1102
+ return this._allYearlyComplex(iterator);
1103
+ }
1104
+ if ((this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") && (this.opts.byMonth || this.opts.byWeekNo || this.opts.byYearDay || this.opts.byMonthDay || this.opts.byDay)) {
1105
+ return this._allMinutelySecondlyComplex(iterator);
1106
+ }
1107
+ if (this.opts.freq === "MONTHLY" && this.opts.byWeekNo && this.opts.byWeekNo.length > 0) {
1108
+ return this._allMonthlyByWeekNo(iterator);
1109
+ }
1110
+ if (this.opts.freq === "MONTHLY" && this.opts.byYearDay && this.opts.byYearDay.length > 0 && !this.opts.byDay && !this.opts.byMonthDay) {
1111
+ return this._allMonthlyByYearDay(iterator);
1112
+ }
1113
+ if ((this.opts.freq === "MINUTELY" || this.opts.freq === "HOURLY" || this.opts.freq === "DAILY") && this.opts.bySetPos) {
1114
+ return this._allDailyMinutelyHourlyWithBySetPos(iterator);
1115
+ }
1116
+ return this._allFallback(iterator);
1117
+ }
1004
1118
  /**
1005
1119
  * Converts rDate entries to ZonedDateTime and merges with existing dates.
1006
1120
  * @param dates - Array of dates to merge with
1007
1121
  * @returns Merged and deduplicated array of dates
1008
1122
  */
1009
1123
  mergeAndDeduplicateRDates(dates) {
1010
- if (!this.opts.rDate) return dates;
1011
- dates.push(...this.opts.rDate);
1124
+ if (this.opts.rDate) {
1125
+ dates.push(...this.opts.rDate);
1126
+ }
1012
1127
  dates.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1013
1128
  const dedup = [];
1014
1129
  for (const d of dates) {
@@ -1155,8 +1270,7 @@ var RRuleTemporal = class _RRuleTemporal {
1155
1270
  if (interval !== 1) rule.push(`INTERVAL=${interval}`);
1156
1271
  if (count !== void 0) rule.push(`COUNT=${count}`);
1157
1272
  if (until) {
1158
- const u = until.toInstant().toString().replace(/[-:]/g, "");
1159
- rule.push(`UNTIL=${u.slice(0, 15)}Z`);
1273
+ rule.push(`UNTIL=${this.formatIcsDateTime(until)}`);
1160
1274
  }
1161
1275
  if (byHour) rule.push(`BYHOUR=${byHour.join(",")}`);
1162
1276
  if (byMinute) rule.push(`BYMINUTE=${byMinute.join(",")}`);
@@ -1177,8 +1291,11 @@ var RRuleTemporal = class _RRuleTemporal {
1177
1291
  }
1178
1292
  return lines.join("\n");
1179
1293
  }
1294
+ formatIcsDateTime(date) {
1295
+ return date.toInstant().toString().replace(/[-:]/g, "").slice(0, 15) + "Z";
1296
+ }
1180
1297
  joinDates(dates) {
1181
- return dates.map((d) => d.toInstant().toString().replace(/[-:]/g, "").slice(0, 15) + "Z");
1298
+ return dates.map((d) => this.formatIcsDateTime(d));
1182
1299
  }
1183
1300
  /**
1184
1301
  * Given any date in a month, return all the ZonedDateTimes in that month
@@ -1198,22 +1315,12 @@ var RRuleTemporal = class _RRuleTemporal {
1198
1315
  return [];
1199
1316
  }
1200
1317
  const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
1201
- let expanded2 = dates.flatMap((z) => this.expandByTime(z)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1202
- return expanded2;
1318
+ return dates.flatMap((z) => this.expandByTime(z)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1203
1319
  }
1204
1320
  if (!byDay) {
1205
- const expanded2 = this.expandByTime(sample);
1206
- return expanded2;
1207
- }
1208
- const dayMap = {
1209
- MO: 1,
1210
- TU: 2,
1211
- WE: 3,
1212
- TH: 4,
1213
- FR: 5,
1214
- SA: 6,
1215
- SU: 7
1216
- };
1321
+ return this.expandByTime(sample);
1322
+ }
1323
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1217
1324
  const tokens = byDay.map((tok) => {
1218
1325
  const m = tok.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
1219
1326
  if (!m) return null;
@@ -1246,8 +1353,7 @@ var RRuleTemporal = class _RRuleTemporal {
1246
1353
  finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
1247
1354
  }
1248
1355
  const hits = finalDays.map((d) => sample.with({ day: d }));
1249
- let expanded = hits.flatMap((z) => this.expandByTime(z)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1250
- return expanded;
1356
+ return hits.flatMap((z) => this.expandByTime(z)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1251
1357
  }
1252
1358
  /**
1253
1359
  * Given any date in a year, return all ZonedDateTimes in that year matching
@@ -1255,20 +1361,11 @@ var RRuleTemporal = class _RRuleTemporal {
1255
1361
  * if BYMONTH is not specified.
1256
1362
  */
1257
1363
  generateYearlyOccurrences(sample) {
1258
- var _a;
1259
- const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : this.opts.byMonthDay ? [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] : [this.originalDtstart.month];
1364
+ const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : this.opts.byMonthDay || this.opts.byDay ? [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] : [this.originalDtstart.month];
1260
1365
  let occs = [];
1261
1366
  const hasOrdinalByDay = this.opts.byDay && this.opts.byDay.some((t) => /^[+-]?\d/.test(t));
1262
1367
  if (hasOrdinalByDay && !this.opts.byMonth) {
1263
- const dayMap = {
1264
- MO: 1,
1265
- TU: 2,
1266
- WE: 3,
1267
- TH: 4,
1268
- FR: 5,
1269
- SA: 6,
1270
- SU: 7
1271
- };
1368
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1272
1369
  for (const tok of this.opts.byDay) {
1273
1370
  const m = tok.match(/^([+-]?\d{1,2})(MO|TU|WE|TH|FR|SA|SU)$/);
1274
1371
  if (!m) continue;
@@ -1296,49 +1393,176 @@ var RRuleTemporal = class _RRuleTemporal {
1296
1393
  const last = sample.with({ month: 12, day: 31 }).dayOfYear;
1297
1394
  for (const d of this.opts.byYearDay) {
1298
1395
  const dayNum = d > 0 ? d : last + d + 1;
1299
- const dt = sample.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1396
+ if (dayNum <= 0 || dayNum > last) continue;
1397
+ const dt = this.opts.freq === "MINUTELY" ? sample.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 }) : sample.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1300
1398
  if (!this.opts.byMonth || this.opts.byMonth.includes(dt.month)) {
1301
1399
  occs.push(...this.expandByTime(dt));
1302
1400
  }
1303
1401
  }
1304
1402
  }
1305
1403
  if (this.opts.byWeekNo) {
1306
- const dayMap = {
1307
- MO: 1,
1308
- TU: 2,
1309
- WE: 3,
1310
- TH: 4,
1311
- FR: 5,
1312
- SA: 6,
1313
- SU: 7
1314
- };
1315
- const wkst = dayMap[this.opts.wkst || "MO"];
1316
- const jan1 = sample.with({ month: 1, day: 1 });
1317
- const delta = (jan1.dayOfWeek - wkst + 7) % 7;
1318
- const firstWeekStart = jan1.subtract({ days: delta });
1319
- const lastWeekDiff = sample.with({ month: 12, day: 31 }).toPlainDate().since(firstWeekStart.toPlainDate()).days;
1320
- const lastWeek = Math.floor(lastWeekDiff / 7) + 1;
1321
- const tokens = ((_a = this.opts.byDay) == null ? void 0 : _a.length) ? this.opts.byDay.map((tok) => {
1322
- var _a2;
1323
- return (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
1324
- }) : [this.opts.wkst || "MO"];
1404
+ const { lastWeek, firstWeekStart, tokens } = this.isoWeekByDay(sample);
1325
1405
  for (const weekNo of this.opts.byWeekNo) {
1406
+ if (weekNo > 0 && weekNo > lastWeek || weekNo < 0 && -weekNo > lastWeek) {
1407
+ continue;
1408
+ }
1326
1409
  const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
1327
1410
  const weekStart = firstWeekStart.add({ weeks: weekIndex });
1328
- for (const tok of tokens) {
1329
- if (!tok) continue;
1330
- const targetDow = dayMap[tok];
1331
- const inst = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
1332
- if (!this.opts.byMonth || this.opts.byMonth.includes(inst.month)) {
1333
- occs.push(...this.expandByTime(inst));
1334
- }
1335
- }
1411
+ occs.push(...this.addByDay(tokens, weekStart));
1336
1412
  }
1337
1413
  }
1338
1414
  occs = occs.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1339
1415
  occs = this.applyBySetPos(occs);
1340
1416
  return occs;
1341
1417
  }
1418
+ addByDay(tokens, weekStart) {
1419
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1420
+ const wkst = dayMap[this.opts.wkst || "MO"];
1421
+ const entries = [];
1422
+ for (const tok of tokens) {
1423
+ if (!tok) continue;
1424
+ const targetDow = dayMap[tok];
1425
+ const inst = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
1426
+ if (!this.opts.byMonth || this.opts.byMonth.includes(inst.month)) {
1427
+ entries.push(...this.expandByTime(inst));
1428
+ }
1429
+ }
1430
+ return entries;
1431
+ }
1432
+ /**
1433
+ * Helper to find the next valid value from a sorted array
1434
+ */
1435
+ findNextValidValue(currentValue, validValues, compare) {
1436
+ return validValues.find((v) => compare(v, currentValue) > 0) || null;
1437
+ }
1438
+ /**
1439
+ * Efficiently find the next valid date for MINUTELY and SECONDLY frequency by jumping over
1440
+ * large gaps when BYXXX constraints don't match.
1441
+ */
1442
+ findNextValidDate(current) {
1443
+ if (this.opts.byWeekNo && this.opts.byYearDay) {
1444
+ const yearStart = current.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 });
1445
+ const yearDays = this.opts.byYearDay.map((yd) => {
1446
+ const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
1447
+ return yd > 0 ? yd : lastDayOfYear + yd + 1;
1448
+ });
1449
+ for (const yd of yearDays) {
1450
+ const date = yearStart.add({ days: yd - 1 });
1451
+ if (this.matchesByWeekNo(date)) {
1452
+ break;
1453
+ }
1454
+ }
1455
+ }
1456
+ if (this.opts.byMonth && !this.opts.byMonth.includes(current.month)) {
1457
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
1458
+ const nextMonth = this.findNextValidValue(current.month, months, (a, b) => a - b);
1459
+ if (nextMonth) {
1460
+ current = current.with({ month: nextMonth, day: 1, hour: 0, minute: 0, second: 0 });
1461
+ } else {
1462
+ current = current.add({ years: 1 }).with({ month: months[0], day: 1, hour: 0, minute: 0, second: 0 });
1463
+ }
1464
+ current = this.applyTimeOverride(current);
1465
+ return current;
1466
+ }
1467
+ if (this.opts.byWeekNo && !this.matchesByWeekNo(current)) {
1468
+ current = current.add({ weeks: 1 }).with({ hour: 0, minute: 0, second: 0 });
1469
+ current = this.applyTimeOverride(current);
1470
+ return current;
1471
+ }
1472
+ if (this.opts.byYearDay && !this.matchesByYearDay(current)) {
1473
+ const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
1474
+ const currentYearDay = current.dayOfYear;
1475
+ const lastDayOfYear = current.with({ month: 12, day: 31 }).dayOfYear;
1476
+ let nextYearDay = yearDays.find((d) => {
1477
+ const dayNum = d > 0 ? d : lastDayOfYear + d + 1;
1478
+ return dayNum > currentYearDay;
1479
+ });
1480
+ if (nextYearDay) {
1481
+ const dayNum = nextYearDay > 0 ? nextYearDay : lastDayOfYear + nextYearDay + 1;
1482
+ if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
1483
+ current = current.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
1484
+ } else {
1485
+ current = current.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1486
+ }
1487
+ } else {
1488
+ const nextYear = current.add({ years: 1 });
1489
+ const nextYearLastDay = nextYear.with({ month: 12, day: 31 }).dayOfYear;
1490
+ const firstYearDay = yearDays[0];
1491
+ if (firstYearDay !== void 0) {
1492
+ const dayNum = firstYearDay > 0 ? firstYearDay : nextYearLastDay + firstYearDay + 1;
1493
+ if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
1494
+ current = nextYear.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
1495
+ } else {
1496
+ current = nextYear.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1497
+ }
1498
+ }
1499
+ }
1500
+ current = this.applyTimeOverride(current);
1501
+ return current;
1502
+ }
1503
+ if (this.opts.byMonthDay && !this.matchesByMonthDay(current)) {
1504
+ const monthDays = [...this.opts.byMonthDay].sort((a, b) => a - b);
1505
+ const lastDayOfMonth = current.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
1506
+ const currentDay = current.day;
1507
+ const validDays = monthDays.map((d) => d > 0 ? d : lastDayOfMonth + d + 1).filter((d) => d > 0 && d <= lastDayOfMonth).sort((a, b) => a - b);
1508
+ const nextDay = this.findNextValidValue(currentDay, validDays, (a, b) => a - b);
1509
+ if (nextDay) {
1510
+ current = current.with({ day: nextDay, hour: 0, minute: 0, second: 0 });
1511
+ } else {
1512
+ const nextMonth = current.add({ months: 1 }).with({ day: 1 });
1513
+ const nextMonthLastDay = nextMonth.add({ months: 1 }).subtract({ days: 1 }).day;
1514
+ const firstMonthDay = monthDays[0];
1515
+ if (firstMonthDay !== void 0) {
1516
+ const dayNum = firstMonthDay > 0 ? firstMonthDay : nextMonthLastDay + firstMonthDay + 1;
1517
+ current = nextMonth.with({
1518
+ day: Math.max(1, Math.min(dayNum, nextMonthLastDay)),
1519
+ hour: 0,
1520
+ minute: 0,
1521
+ second: 0
1522
+ });
1523
+ } else {
1524
+ current = current.add({ months: 1 }).with({ day: 1, hour: 0, minute: 0, second: 0 });
1525
+ }
1526
+ }
1527
+ current = this.applyTimeOverride(current);
1528
+ return current;
1529
+ }
1530
+ if (this.opts.byDay && !this.matchesByDay(current)) {
1531
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1532
+ const targetDays = this.opts.byDay.map((tok) => {
1533
+ var _a;
1534
+ return (_a = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a[1];
1535
+ }).filter(Boolean).map((day) => dayMap[day]).filter(Boolean);
1536
+ const nextDayOfWeek = this.findNextValidValue(current.dayOfWeek, targetDays.sort(), (a, b) => a - b);
1537
+ if (nextDayOfWeek) {
1538
+ const delta = (nextDayOfWeek - current.dayOfWeek + 7) % 7;
1539
+ current = current.add({ days: delta }).with({ hour: 0, minute: 0, second: 0 });
1540
+ } else {
1541
+ const delta = (targetDays[0] - current.dayOfWeek + 7) % 7;
1542
+ current = current.add({ days: delta + 7 }).with({ hour: 0, minute: 0, second: 0 });
1543
+ }
1544
+ current = this.applyTimeOverride(current);
1545
+ return current;
1546
+ }
1547
+ switch (this.opts.freq) {
1548
+ case "SECONDLY":
1549
+ case "MINUTELY":
1550
+ current = current.add({ days: 1 }).with({ hour: 0, minute: 0, second: 0 });
1551
+ break;
1552
+ case "HOURLY":
1553
+ current = current.add({ days: 1 }).with({ hour: 0, minute: 0, second: 0 });
1554
+ break;
1555
+ case "DAILY":
1556
+ case "WEEKLY":
1557
+ current = current.add({ months: 1 }).with({ day: 1, hour: 0, minute: 0, second: 0 });
1558
+ break;
1559
+ case "MONTHLY":
1560
+ case "YEARLY":
1561
+ current = current.add({ years: 1 }).with({ month: 1, day: 1, hour: 0, minute: 0, second: 0 });
1562
+ break;
1563
+ }
1564
+ return this.applyTimeOverride(current);
1565
+ }
1342
1566
  applyBySetPos(list2) {
1343
1567
  const { bySetPos } = this.opts;
1344
1568
  if (!bySetPos || !bySetPos.length) return list2;
@@ -1351,6 +1575,37 @@ var RRuleTemporal = class _RRuleTemporal {
1351
1575
  }
1352
1576
  return out.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1353
1577
  }
1578
+ isoWeekByDay(sample) {
1579
+ var _a;
1580
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1581
+ const wkst = dayMap[this.opts.wkst || "MO"];
1582
+ const jan1 = sample.with({ month: 1, day: 1 });
1583
+ const jan4 = sample.with({ month: 1, day: 4 });
1584
+ const delta = (jan4.dayOfWeek - wkst + 7) % 7;
1585
+ const firstWeekStart = jan4.subtract({ days: delta });
1586
+ const isLeapYear = jan1.inLeapYear;
1587
+ const lastWeek = jan1.dayOfWeek === 4 || isLeapYear && jan1.dayOfWeek === 3 ? 53 : 52;
1588
+ const tokens = ((_a = this.opts.byDay) == null ? void 0 : _a.length) ? this.opts.byDay.map((tok) => {
1589
+ var _a2;
1590
+ return (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
1591
+ }) : [Object.entries(dayMap).find(([, d]) => d === this.originalDtstart.dayOfWeek)[0]];
1592
+ return { lastWeek, firstWeekStart, tokens };
1593
+ }
1594
+ /**
1595
+ * Generate occurrences for a specific week number in a given year
1596
+ */
1597
+ generateOccurrencesForWeekInYear(year, weekNo) {
1598
+ const occs = [];
1599
+ const sample = this.originalDtstart.with({ year, month: 1, day: 1 });
1600
+ const { lastWeek, firstWeekStart, tokens } = this.isoWeekByDay(sample);
1601
+ if (weekNo > 0 && weekNo > lastWeek || weekNo < 0 && -weekNo > lastWeek) {
1602
+ return occs;
1603
+ }
1604
+ const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
1605
+ const weekStart = firstWeekStart.add({ weeks: weekIndex });
1606
+ occs.push(...this.addByDay(tokens, weekStart));
1607
+ return occs.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
1608
+ }
1354
1609
  };
1355
1610
 
1356
1611
  // src/totext.ts