rrule-temporal 2.0.2 → 2.1.0

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.
@@ -4605,6 +4605,45 @@ const NS_PER_MINUTE = BigInt(60) * NS_PER_SECOND;
4605
4605
  const NS_PER_HOUR = BigInt(60) * NS_PER_MINUTE;
4606
4606
  const NS_PER_DAY = BigInt(24) * NS_PER_HOUR;
4607
4607
  const NS_PER_WEEK = BigInt(7) * NS_PER_DAY;
4608
+ const TEMPORAL_MAX_EPOCH_MILLISECONDS = 864e13;
4609
+ function gcd(left, right) {
4610
+ let a = Math.abs(left);
4611
+ let b = Math.abs(right);
4612
+ while (b !== 0) {
4613
+ const next = a % b;
4614
+ a = b;
4615
+ b = next;
4616
+ }
4617
+ return a;
4618
+ }
4619
+ function weekdayMask(days) {
4620
+ let mask = 0;
4621
+ for (const day of days ?? []) mask |= 1 << day - 1;
4622
+ return mask;
4623
+ }
4624
+ function includesIsoWeekday(mask, day) {
4625
+ return mask === 0 || (mask & 1 << day - 1) !== 0;
4626
+ }
4627
+ function floorDivBigInt(dividend, divisor) {
4628
+ const quotient = dividend / divisor;
4629
+ return dividend % divisor < 0n ? quotient - 1n : quotient;
4630
+ }
4631
+ function ceilDivBigInt(dividend, divisor) {
4632
+ return -floorDivBigInt(-dividend, divisor);
4633
+ }
4634
+ function isSafeTemporalEpochMilliseconds(value) {
4635
+ return Number.isSafeInteger(value) && value >= -TEMPORAL_MAX_EPOCH_MILLISECONDS && value <= TEMPORAL_MAX_EPOCH_MILLISECONDS;
4636
+ }
4637
+ /** Proleptic Gregorian day number where 1970-01-01 is zero. */
4638
+ function gregorianEpochDay(year, month, day) {
4639
+ const adjustedYear = year - (month <= 2 ? 1 : 0);
4640
+ const era = Math.floor(adjustedYear / 400);
4641
+ const yearOfEra = adjustedYear - era * 400;
4642
+ const adjustedMonth = month + (month > 2 ? -3 : 9);
4643
+ const dayOfYear = Math.floor((153 * adjustedMonth + 2) / 5) + day - 1;
4644
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
4645
+ return era * 146097 + dayOfEra - 719468;
4646
+ }
4608
4647
  function isoDayOfWeekOfEpochDay(epochDay) {
4609
4648
  return ((epochDay + 3) % 7 + 7) % 7 + 1;
4610
4649
  }
@@ -5537,6 +5576,341 @@ var RRuleTemporal = class RRuleTemporal {
5537
5576
  for (const hour of hours) for (const minute of minutes) for (const second of seconds) offsets.push(((hour * 60 + minute) * 60 + second) * MS_PER_SECOND + baseMilliseconds);
5538
5577
  return offsets;
5539
5578
  }
5579
+ createNumericQueryPlan(kind, maximumCount, select, directLowerBound) {
5580
+ const first = select(0);
5581
+ const last = select(maximumCount - 1);
5582
+ if (!first || !last || !isSafeTemporalEpochMilliseconds(first.epochMilliseconds) || !isSafeTemporalEpochMilliseconds(last.epochMilliseconds) || first.epochMilliseconds > last.epochMilliseconds) return null;
5583
+ const findLowerBound = (targetEpochNanoseconds, strict, high) => {
5584
+ if (directLowerBound) return Math.max(0, Math.min(high, directLowerBound(targetEpochNanoseconds, strict)));
5585
+ let low = 0;
5586
+ let upper = high;
5587
+ while (low < upper) {
5588
+ const middle = low + Math.floor((upper - low) / 2);
5589
+ const candidate = select(middle);
5590
+ if (!candidate) {
5591
+ upper = middle;
5592
+ continue;
5593
+ }
5594
+ const candidateEpochNanoseconds = BigInt(candidate.epochMilliseconds) * NS_PER_MILLISECOND;
5595
+ if (strict ? candidateEpochNanoseconds > targetEpochNanoseconds : candidateEpochNanoseconds >= targetEpochNanoseconds) upper = middle;
5596
+ else low = middle + 1;
5597
+ }
5598
+ return low;
5599
+ };
5600
+ const untilEpochNanoseconds = this.opts.until?.epochNanoseconds;
5601
+ const count = untilEpochNanoseconds === void 0 ? maximumCount : findLowerBound(untilEpochNanoseconds, true, maximumCount);
5602
+ return {
5603
+ kind,
5604
+ count,
5605
+ maximumCount,
5606
+ select: (index) => {
5607
+ if (!Number.isSafeInteger(index) || index < 0 || index >= maximumCount) return null;
5608
+ return select(index);
5609
+ },
5610
+ lowerBound: (targetEpochNanoseconds, strict) => findLowerBound(targetEpochNanoseconds, strict, count)
5611
+ };
5612
+ }
5613
+ buildFixedStepNumericQueryPlan(maximumCount) {
5614
+ let unitMilliseconds;
5615
+ switch (this.opts.freq) {
5616
+ case "HOURLY":
5617
+ unitMilliseconds = MS_PER_HOUR;
5618
+ break;
5619
+ case "MINUTELY":
5620
+ unitMilliseconds = MS_PER_MINUTE;
5621
+ break;
5622
+ case "SECONDLY":
5623
+ unitMilliseconds = MS_PER_SECOND;
5624
+ break;
5625
+ default: return null;
5626
+ }
5627
+ if (![
5628
+ "UTC",
5629
+ "Etc/UTC",
5630
+ "Etc/GMT"
5631
+ ].includes(this.tzid) && !/^[-+]\d{2}:?\d{2}(?::?\d{2})?$/.test(this.tzid) && this.opts.freq === "HOURLY" && this.opts.interval === 1) return null;
5632
+ const startMilliseconds = this.originalDtstart.epochMilliseconds;
5633
+ const stepMilliseconds = unitMilliseconds * this.opts.interval;
5634
+ if (!Number.isSafeInteger(stepMilliseconds) || stepMilliseconds <= 0) return null;
5635
+ const select = (index) => {
5636
+ const epochMilliseconds = startMilliseconds + index * stepMilliseconds;
5637
+ if (!isSafeTemporalEpochMilliseconds(epochMilliseconds)) return null;
5638
+ return {
5639
+ epochMilliseconds,
5640
+ periodIndex: index,
5641
+ occurrenceIndex: index
5642
+ };
5643
+ };
5644
+ const startEpochNanoseconds = BigInt(startMilliseconds) * NS_PER_MILLISECOND;
5645
+ const stepEpochNanoseconds = BigInt(stepMilliseconds) * NS_PER_MILLISECOND;
5646
+ const countAsBigInt = BigInt(maximumCount);
5647
+ const directLowerBound = (targetEpochNanoseconds, strict) => {
5648
+ const delta = targetEpochNanoseconds - startEpochNanoseconds;
5649
+ const rawIndex = strict ? floorDivBigInt(delta, stepEpochNanoseconds) + 1n : ceilDivBigInt(delta, stepEpochNanoseconds);
5650
+ if (rawIndex <= 0n) return 0;
5651
+ if (rawIndex >= countAsBigInt) return maximumCount;
5652
+ return Number(rawIndex);
5653
+ };
5654
+ return this.createNumericQueryPlan("fixed-step", maximumCount, select, directLowerBound);
5655
+ }
5656
+ resolveNumericWallMilliseconds(wallMilliseconds) {
5657
+ if (!isSafeTemporalEpochMilliseconds(wallMilliseconds)) return null;
5658
+ if (this.tzid === "UTC") return wallMilliseconds;
5659
+ const resolution = this.getZoneResolver().epochMsForWall(wallMilliseconds);
5660
+ if (resolution.pushed || !isSafeTemporalEpochMilliseconds(resolution.epochMs)) return null;
5661
+ return resolution.epochMs;
5662
+ }
5663
+ numericQueryGapHazard(timeOfDayMilliseconds, lastEpochMilliseconds) {
5664
+ if (this.tzid === "UTC") return false;
5665
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5666
+ const MAX_SPAN_MS = 200 * 366 * MS_PER_DAY;
5667
+ if (lastEpochMilliseconds - startEpochMilliseconds > MAX_SPAN_MS) return true;
5668
+ return this.getZoneResolver().timeOfDayMayHitGap(timeOfDayMilliseconds, startEpochMilliseconds - MS_PER_DAY, lastEpochMilliseconds + MS_PER_DAY);
5669
+ }
5670
+ buildDailyNumericQueryPlan(maximumCount) {
5671
+ const interval = this.opts.interval;
5672
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5673
+ const startWallMilliseconds = this.tzid === "UTC" ? startEpochMilliseconds : this.wallMsOf(this.originalDtstart);
5674
+ const startEpochDay = Math.floor(startWallMilliseconds / MS_PER_DAY);
5675
+ const startDayOfWeek = isoDayOfWeekOfEpochDay(startEpochDay);
5676
+ const allowedDayMask = weekdayMask(this.simpleByDayIsoDays);
5677
+ if (!Boolean(this.opts.byHour || this.opts.byMinute || this.opts.bySecond)) {
5678
+ const timeOfDayMilliseconds = startWallMilliseconds - startEpochDay * MS_PER_DAY;
5679
+ const firstMatchingStep = this.simpleByDayIsoDays?.length ? this.findFirstMatchingDailyStep(startDayOfWeek, interval, this.simpleByDayIsoDays) : 0;
5680
+ if (firstMatchingStep === null) return null;
5681
+ const cyclePeriods = 7 / gcd(interval, 7);
5682
+ const matchingPeriodOffsets = [];
5683
+ for (let offset = 0; offset < cyclePeriods; offset++) if (includesIsoWeekday(allowedDayMask, addIsoDays(startDayOfWeek, (firstMatchingStep + offset) * interval))) matchingPeriodOffsets.push(offset);
5684
+ if (matchingPeriodOffsets.length === 0) return null;
5685
+ const select = (index) => {
5686
+ const cycleIndex = Math.floor(index / matchingPeriodOffsets.length);
5687
+ const offsetIndex = index % matchingPeriodOffsets.length;
5688
+ const periodIndex = cycleIndex * cyclePeriods + matchingPeriodOffsets[offsetIndex];
5689
+ const dayDelta = (firstMatchingStep + periodIndex) * interval;
5690
+ if (!Number.isSafeInteger(periodIndex) || !Number.isSafeInteger(dayDelta)) return null;
5691
+ const wallMilliseconds = startWallMilliseconds + dayDelta * MS_PER_DAY;
5692
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5693
+ if (epochMilliseconds === null) return null;
5694
+ return {
5695
+ epochMilliseconds,
5696
+ periodIndex,
5697
+ occurrenceIndex: index
5698
+ };
5699
+ };
5700
+ const plan = this.createNumericQueryPlan("daily", maximumCount, select);
5701
+ const last = plan?.select(maximumCount - 1);
5702
+ if (last && this.numericQueryGapHazard(timeOfDayMilliseconds, last.epochMilliseconds)) return null;
5703
+ return plan;
5704
+ }
5705
+ const timeSlotOffsets = this.timeSlotOffsetsMs;
5706
+ if (!timeSlotOffsets?.length || !this.hasUniqueTimeSlotOffsets) return null;
5707
+ const firstDayOffset = this.simpleByDayIsoDays?.length ? this.findFirstMatchingDailyStep(startDayOfWeek, 1, this.simpleByDayIsoDays) : 0;
5708
+ if (firstDayOffset === null) return null;
5709
+ const firstEpochDay = startEpochDay + firstDayOffset;
5710
+ const firstDayOfWeek = addIsoDays(startDayOfWeek, firstDayOffset);
5711
+ const cyclePeriods = 7 / gcd(interval, 7);
5712
+ const firstCandidates = [];
5713
+ if (includesIsoWeekday(allowedDayMask, firstDayOfWeek)) for (const timeSlotOffset of timeSlotOffsets) {
5714
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(firstEpochDay * MS_PER_DAY + timeSlotOffset);
5715
+ if (epochMilliseconds === null) return null;
5716
+ if (epochMilliseconds >= startEpochMilliseconds) firstCandidates.push({
5717
+ epochMilliseconds,
5718
+ periodIndex: 0,
5719
+ occurrenceIndex: firstCandidates.length
5720
+ });
5721
+ }
5722
+ const cycleSlots = [];
5723
+ for (let periodOffset = 0; periodOffset < cyclePeriods; periodOffset++) {
5724
+ if (!includesIsoWeekday(allowedDayMask, addIsoDays(firstDayOfWeek, (1 + periodOffset) * interval))) continue;
5725
+ for (const timeSlotOffset of timeSlotOffsets) cycleSlots.push({
5726
+ periodOffset,
5727
+ timeSlotOffset
5728
+ });
5729
+ }
5730
+ if (firstCandidates.length === 0 && cycleSlots.length === 0) return null;
5731
+ const select = (index) => {
5732
+ if (index < firstCandidates.length) return {
5733
+ ...firstCandidates[index],
5734
+ occurrenceIndex: index
5735
+ };
5736
+ if (cycleSlots.length === 0) return null;
5737
+ const remainingIndex = index - firstCandidates.length;
5738
+ const cycleIndex = Math.floor(remainingIndex / cycleSlots.length);
5739
+ const slot = cycleSlots[remainingIndex % cycleSlots.length];
5740
+ const periodIndex = 1 + cycleIndex * cyclePeriods + slot.periodOffset;
5741
+ const dayDelta = firstDayOffset + periodIndex * interval;
5742
+ if (!Number.isSafeInteger(periodIndex) || !Number.isSafeInteger(dayDelta)) return null;
5743
+ const wallMilliseconds = (startEpochDay + dayDelta) * MS_PER_DAY + slot.timeSlotOffset;
5744
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5745
+ if (epochMilliseconds === null) return null;
5746
+ return {
5747
+ epochMilliseconds,
5748
+ periodIndex,
5749
+ occurrenceIndex: index
5750
+ };
5751
+ };
5752
+ const plan = this.createNumericQueryPlan("daily", maximumCount, select);
5753
+ const last = plan?.select(maximumCount - 1);
5754
+ if (last && timeSlotOffsets.some((offset) => this.numericQueryGapHazard(offset, last.epochMilliseconds))) return null;
5755
+ return plan;
5756
+ }
5757
+ buildWeeklyNumericQueryPlan(maximumCount) {
5758
+ const timeSlotOffsets = this.timeSlotOffsetsMs;
5759
+ if (!timeSlotOffsets?.length || !this.hasUniqueTimeSlotOffsets) return null;
5760
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5761
+ const startWallMilliseconds = this.tzid === "UTC" ? startEpochMilliseconds : this.wallMsOf(this.originalDtstart);
5762
+ const startEpochDay = Math.floor(startWallMilliseconds / MS_PER_DAY);
5763
+ const startDayOfWeek = isoDayOfWeekOfEpochDay(startEpochDay);
5764
+ const wkstDay = weekdayToIsoDay[extractWeekdayToken(this.opts.wkst || "MO") ?? "MO"] ?? 1;
5765
+ const dayOffsets = (this.opts.byDay ? [...this.allByDayIsoDays ?? []] : [startDayOfWeek]).map((day) => (day - wkstDay + 7) % 7).sort((a, b) => a - b);
5766
+ if (dayOffsets.length === 0) return null;
5767
+ const firstWeekStartDay = startEpochDay - (startDayOfWeek - wkstDay + 7) % 7;
5768
+ const weeklySlots = dayOffsets.flatMap((dayOffset) => timeSlotOffsets.map((timeSlotOffset) => ({
5769
+ dayOffset,
5770
+ timeSlotOffset
5771
+ })));
5772
+ const firstCandidates = [];
5773
+ for (const slot of weeklySlots) {
5774
+ const wallMilliseconds = (firstWeekStartDay + slot.dayOffset) * MS_PER_DAY + slot.timeSlotOffset;
5775
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5776
+ if (epochMilliseconds === null) return null;
5777
+ if (epochMilliseconds >= startEpochMilliseconds) firstCandidates.push({
5778
+ epochMilliseconds,
5779
+ periodIndex: 0,
5780
+ occurrenceIndex: firstCandidates.length
5781
+ });
5782
+ }
5783
+ const select = (index) => {
5784
+ if (index < firstCandidates.length) return {
5785
+ ...firstCandidates[index],
5786
+ occurrenceIndex: index
5787
+ };
5788
+ const remainingIndex = index - firstCandidates.length;
5789
+ const periodIndex = 1 + Math.floor(remainingIndex / weeklySlots.length);
5790
+ const slot = weeklySlots[remainingIndex % weeklySlots.length];
5791
+ const weekDelta = periodIndex * this.opts.interval * 7;
5792
+ if (!Number.isSafeInteger(periodIndex) || !Number.isSafeInteger(weekDelta)) return null;
5793
+ const wallMilliseconds = (firstWeekStartDay + weekDelta + slot.dayOffset) * MS_PER_DAY + slot.timeSlotOffset;
5794
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5795
+ if (epochMilliseconds === null) return null;
5796
+ return {
5797
+ epochMilliseconds,
5798
+ periodIndex,
5799
+ occurrenceIndex: index
5800
+ };
5801
+ };
5802
+ const plan = this.createNumericQueryPlan("weekly", maximumCount, select);
5803
+ const last = plan?.select(maximumCount - 1);
5804
+ if (last && timeSlotOffsets.some((offset) => this.numericQueryGapHazard(offset, last.epochMilliseconds))) return null;
5805
+ return plan;
5806
+ }
5807
+ buildMonthlyNumericQueryPlan(maximumCount) {
5808
+ const interval = this.opts.interval;
5809
+ const timeSlotOffsets = this.timeSlotOffsetsMs;
5810
+ if (!timeSlotOffsets?.length || !this.hasUniqueTimeSlotOffsets) return null;
5811
+ if (this.opts.byMonth?.some((value) => typeof value !== "number")) return null;
5812
+ if (this.opts.bySetPos && new Set(this.opts.bySetPos).size !== this.opts.bySetPos.length) return null;
5813
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5814
+ const startMonthIndex = this.originalDtstart.year * 12 + (this.originalDtstart.month - 1);
5815
+ const wallsForPeriod = (periodIndex) => {
5816
+ const monthDelta = periodIndex * interval;
5817
+ const monthIndex = startMonthIndex + monthDelta;
5818
+ if (!Number.isSafeInteger(monthDelta) || !Number.isSafeInteger(monthIndex)) return null;
5819
+ const { year, month } = this.monthIndexToYearMonth(monthIndex);
5820
+ return this.generateMonthlyOccurrenceEpochsUtc(year, month);
5821
+ };
5822
+ const firstWalls = wallsForPeriod(0);
5823
+ if (!firstWalls) return null;
5824
+ const firstCandidates = [];
5825
+ for (const wallMilliseconds of firstWalls) {
5826
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5827
+ if (epochMilliseconds === null) return null;
5828
+ if (epochMilliseconds >= startEpochMilliseconds) firstCandidates.push({
5829
+ epochMilliseconds,
5830
+ periodIndex: 0,
5831
+ occurrenceIndex: firstCandidates.length
5832
+ });
5833
+ }
5834
+ const cyclePeriods = 4800 / gcd(interval, 4800);
5835
+ const requiredCycleOccurrences = Math.max(0, maximumCount - firstCandidates.length);
5836
+ const cyclePrefixCounts = [0];
5837
+ for (let periodOffset = 0; periodOffset < cyclePeriods && cyclePrefixCounts.at(-1) < requiredCycleOccurrences; periodOffset++) {
5838
+ const walls = wallsForPeriod(1 + periodOffset);
5839
+ if (!walls) return null;
5840
+ cyclePrefixCounts.push(cyclePrefixCounts[periodOffset] + walls.length);
5841
+ }
5842
+ const completedCycle = cyclePrefixCounts.length - 1 === cyclePeriods;
5843
+ const occurrencesPerPrecomputedSpan = cyclePrefixCounts.at(-1);
5844
+ if (occurrencesPerPrecomputedSpan === 0 && firstCandidates.length < maximumCount) return null;
5845
+ const select = (index) => {
5846
+ if (index < firstCandidates.length) return {
5847
+ ...firstCandidates[index],
5848
+ occurrenceIndex: index
5849
+ };
5850
+ if (occurrencesPerPrecomputedSpan === 0) return null;
5851
+ const remainingIndex = index - firstCandidates.length;
5852
+ const cycleIndex = completedCycle ? Math.floor(remainingIndex / occurrencesPerPrecomputedSpan) : 0;
5853
+ const indexWithinCycle = completedCycle ? remainingIndex % occurrencesPerPrecomputedSpan : remainingIndex;
5854
+ if (indexWithinCycle >= occurrencesPerPrecomputedSpan) return null;
5855
+ let low = 1;
5856
+ let high = cyclePrefixCounts.length - 1;
5857
+ while (low < high) {
5858
+ const middle = low + Math.floor((high - low) / 2);
5859
+ if (cyclePrefixCounts[middle] > indexWithinCycle) high = middle;
5860
+ else low = middle + 1;
5861
+ }
5862
+ const periodOffset = low - 1;
5863
+ const periodIndex = 1 + cycleIndex * cyclePeriods + periodOffset;
5864
+ if (!Number.isSafeInteger(periodIndex)) return null;
5865
+ const walls = wallsForPeriod(periodIndex);
5866
+ if (!walls) return null;
5867
+ const wallMilliseconds = walls[indexWithinCycle - cyclePrefixCounts[periodOffset]];
5868
+ if (wallMilliseconds === void 0) return null;
5869
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5870
+ if (epochMilliseconds === null) return null;
5871
+ return {
5872
+ epochMilliseconds,
5873
+ periodIndex,
5874
+ occurrenceIndex: index
5875
+ };
5876
+ };
5877
+ const plan = this.createNumericQueryPlan("monthly", maximumCount, select);
5878
+ const last = plan?.select(maximumCount - 1);
5879
+ if (last && timeSlotOffsets.some((offset) => this.numericQueryGapHazard(offset, last.epochMilliseconds))) return null;
5880
+ return plan;
5881
+ }
5882
+ buildNumericQueryPlan() {
5883
+ const maximumCount = this.opts.count;
5884
+ const interval = this.opts.interval;
5885
+ if (maximumCount === void 0 || !Number.isSafeInteger(maximumCount) || maximumCount <= 0 || !Number.isSafeInteger(interval) || interval <= 0 || !Number.isSafeInteger(this.maxIterations) || this.maxIterations <= 0 || this.includeDtstart || this.opts.rscale !== void 0 || this.opts.rDate !== void 0 || this.opts.exDate !== void 0 || !this.canUseEpochMillisecondsPrecisionFlag || this.originalDtstart.timeZoneId !== this.tzid || !["iso8601", "gregory"].includes(this.originalDtstart.calendarId)) return null;
5886
+ const hasCalendarFilters = Boolean(this.opts.byMonth || this.opts.byMonthDay || this.opts.byYearDay || this.opts.byWeekNo || this.opts.bySetPos);
5887
+ switch (this.opts.freq) {
5888
+ case "HOURLY":
5889
+ case "MINUTELY":
5890
+ case "SECONDLY":
5891
+ if (hasCalendarFilters || this.opts.byDay || this.opts.byHour || this.opts.byMinute || this.opts.bySecond) return null;
5892
+ return this.buildFixedStepNumericQueryPlan(maximumCount);
5893
+ case "DAILY":
5894
+ if (hasCalendarFilters || this.hasOrdinalByDay || !this.hasUniqueTimeSlotOffsets) return null;
5895
+ return this.buildDailyNumericQueryPlan(maximumCount);
5896
+ case "WEEKLY":
5897
+ if (hasCalendarFilters || this.hasOrdinalByDay || !this.hasUniqueTimeSlotOffsets) return null;
5898
+ return this.buildWeeklyNumericQueryPlan(maximumCount);
5899
+ case "MONTHLY":
5900
+ if (this.opts.byYearDay || this.opts.byWeekNo || !(this.opts.byDay || this.opts.byMonthDay) || !this.hasUniqueTimeSlotOffsets) return null;
5901
+ return this.buildMonthlyNumericQueryPlan(maximumCount);
5902
+ default: return null;
5903
+ }
5904
+ }
5905
+ getNumericQueryPlan() {
5906
+ if (this.numericQueryPlanCache !== void 0) return this.numericQueryPlanCache;
5907
+ try {
5908
+ this.numericQueryPlanCache = this.buildNumericQueryPlan();
5909
+ } catch {
5910
+ this.numericQueryPlanCache = null;
5911
+ }
5912
+ return this.numericQueryPlanCache;
5913
+ }
5540
5914
  findFirstMatchingDailyStep(startDayOfWeek, stepDays, allowedDays) {
5541
5915
  let dayOfWeek = startDayOfWeek;
5542
5916
  for (let steps = 0; steps < 7; steps++) {
@@ -5816,7 +6190,7 @@ var RRuleTemporal = class RRuleTemporal {
5816
6190
  gregorianIsoDayOfWeek(year, month, day) {
5817
6191
  let adjustedYear = year;
5818
6192
  if (month < 3) adjustedYear -= 1;
5819
- const sundayZero = (adjustedYear + Math.floor(adjustedYear / 4) - Math.floor(adjustedYear / 100) + Math.floor(adjustedYear / 400) + GREGORIAN_WEEKDAY_OFFSETS[month - 1] + day) % 7;
6193
+ const sundayZero = ((adjustedYear + Math.floor(adjustedYear / 4) - Math.floor(adjustedYear / 100) + Math.floor(adjustedYear / 400) + GREGORIAN_WEEKDAY_OFFSETS[month - 1] + day) % 7 + 7) % 7;
5820
6194
  return sundayZero === 0 ? 7 : sundayZero;
5821
6195
  }
5822
6196
  monthIndexToYearMonth(monthIndex) {
@@ -5869,7 +6243,8 @@ var RRuleTemporal = class RRuleTemporal {
5869
6243
  generateMonthlyOccurrenceEpochsUtc(year, month) {
5870
6244
  const days = this.generateMonthlyOccurrenceDaysUtc(year, month);
5871
6245
  if (days.length === 0) return [];
5872
- const monthStartMs = Date.UTC(year, month - 1, 1, 0, 0, 0, 0);
6246
+ const monthStartMs = gregorianEpochDay(year, month, 1) * MS_PER_DAY;
6247
+ if (!isSafeTemporalEpochMilliseconds(monthStartMs)) return [];
5873
6248
  const timeSlotOffsets = this.timeSlotOffsetsMs ?? [0];
5874
6249
  if (this.opts.bySetPos && this.opts.bySetPos.length > 0) {
5875
6250
  if (timeSlotOffsets.length === 1) {
@@ -6542,6 +6917,7 @@ var RRuleTemporal = class RRuleTemporal {
6542
6917
  if (!possibleDate) return [];
6543
6918
  }
6544
6919
  if (!this.opts.count && !this.opts.until && !iterator) throw new Error("all() requires iterator when no COUNT/UNTIL");
6920
+ if (iterator && (this.opts.rDate || this.opts.exDate)) return this.iterateRecurrenceSet(iterator);
6545
6921
  const utcFastPathDates = this.allUtcFastPath(iterator);
6546
6922
  if (utcFastPathDates) return utcFastPathDates;
6547
6923
  const tzFastPathDates = this.allTzEpochFastPath(iterator);
@@ -6643,38 +7019,73 @@ var RRuleTemporal = class RRuleTemporal {
6643
7019
  });
6644
7020
  }
6645
7021
  /**
6646
- * Applies count limit and merges rDates with the rule-generated dates.
7022
+ * Finalizes the recurrence set in RFC 5545 order: bound the RRULE-generated
7023
+ * dates by COUNT, union RDATE, then subtract EXDATE.
6647
7024
  * @param dates - Array of dates generated by the rule
6648
7025
  * @param iterator - Optional iterator function
6649
- * @returns Final array of dates after merging and applying count limit
7026
+ * @returns Final recurrence set
6650
7027
  */
6651
7028
  applyCountLimitAndMergeRDates(dates, iterator) {
6652
- const merged = this.mergeAndDeduplicateRDates(dates);
7029
+ const ruleDates = this.opts.count === void 0 ? dates : dates.slice(0, Math.max(this.opts.count, 0));
7030
+ const merged = this.mergeAndDeduplicateRDates(ruleDates);
6653
7031
  const excluded = this.excludeExDates(merged);
6654
- const hasCountLimit = this.opts.count !== void 0;
6655
- if (!hasCountLimit && !iterator) return excluded;
6656
- let emitted = 0;
6657
- const max = hasCountLimit ? this.opts.count : Infinity;
7032
+ if (!iterator || !this.opts.rDate && !this.opts.exDate) return excluded;
7033
+ return this.applyIterator(excluded, iterator);
7034
+ }
7035
+ /**
7036
+ * Streams the final recurrence set without materializing the complete RRULE.
7037
+ * A rule-only instance keeps COUNT/UNTIL scoped to RRULE generation while
7038
+ * sorted RDATE values are merged and EXDATE values are filtered at emission.
7039
+ */
7040
+ iterateRecurrenceSet(iterator) {
6658
7041
  const finalDates = [];
6659
- for (const d of excluded) {
6660
- if (emitted >= max) break;
6661
- if (iterator && !iterator(d, emitted)) break;
7042
+ const rDates = [...this.opts.rDate ?? []].sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
7043
+ let rDateIndex = 0;
7044
+ let lastSeenEpoch;
7045
+ let stopped = false;
7046
+ const emit = (date) => {
7047
+ const epoch = date.epochNanoseconds;
7048
+ if (lastSeenEpoch === epoch) return true;
7049
+ lastSeenEpoch = epoch;
7050
+ if (this.isExcluded(date)) return true;
7051
+ if (!iterator(date, finalDates.length)) {
7052
+ stopped = true;
7053
+ return false;
7054
+ }
7055
+ finalDates.push(date);
7056
+ return true;
7057
+ };
7058
+ const emitRDatesBefore = (epoch) => {
7059
+ while (rDateIndex < rDates.length && rDates[rDateIndex].epochNanoseconds < epoch) if (!emit(rDates[rDateIndex++])) return false;
7060
+ return true;
7061
+ };
7062
+ const ruleIterator = (date) => {
7063
+ if (!emitRDatesBefore(date.epochNanoseconds)) return false;
7064
+ if (!emit(date)) return false;
7065
+ while (rDateIndex < rDates.length && rDates[rDateIndex].epochNanoseconds === date.epochNanoseconds) rDateIndex++;
7066
+ return true;
7067
+ };
7068
+ if (this.opts.count === void 0 || this.opts.count > 0) new RRuleTemporal({
7069
+ ...this.cloneOptions(),
7070
+ rDate: void 0,
7071
+ exDate: void 0,
7072
+ cache: false
7073
+ }).allInternal(ruleIterator);
7074
+ while (!stopped && rDateIndex < rDates.length) if (!emit(rDates[rDateIndex++])) break;
7075
+ return finalDates;
7076
+ }
7077
+ applyIterator(dates, iterator) {
7078
+ const finalDates = [];
7079
+ for (const d of dates) {
7080
+ if (!iterator(d, finalDates.length)) break;
6662
7081
  finalDates.push(d);
6663
- emitted++;
6664
7082
  }
6665
7083
  return finalDates;
6666
7084
  }
6667
- /**
6668
- * Checks if the count limit should break the loop based on rDate presence.
6669
- * @param matchCount - Current number of matches
6670
- * @returns true if the loop should break
6671
- */
7085
+ /** Stops RRULE generation once COUNT rule occurrences have been found. */
6672
7086
  shouldBreakForCountLimit(matchCount) {
6673
7087
  if (this.opts.count === void 0) return false;
6674
- if (!this.opts.rDate) return matchCount >= this.opts.count;
6675
- const rDateCount = this.opts.rDate.length;
6676
- const targetRuleCount = Math.max(this.opts.count - rDateCount, 0);
6677
- return matchCount >= targetRuleCount + Math.min(targetRuleCount, 10);
7088
+ return matchCount >= this.opts.count;
6678
7089
  }
6679
7090
  hasTimeOfDayBetween(startTime, endTime) {
6680
7091
  if (Temporal.PlainTime.compare(startTime, endTime) >= 0) return false;
@@ -6695,6 +7106,74 @@ var RRuleTemporal = class RRuleTemporal {
6695
7106
  }
6696
7107
  return false;
6697
7108
  }
7109
+ assertNumericCandidateReachable(candidate) {
7110
+ if (candidate && candidate.periodIndex >= this.maxIterations) throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
7111
+ }
7112
+ numericExhaustionCandidate(plan) {
7113
+ if (plan.count < plan.maximumCount) return plan.select(plan.count);
7114
+ return plan.count > 0 ? plan.select(plan.count - 1) : null;
7115
+ }
7116
+ tryNumericNext(targetEpochNanoseconds, inclusive) {
7117
+ const plan = this.getNumericQueryPlan();
7118
+ if (!plan) return { handled: false };
7119
+ const index = plan.lowerBound(targetEpochNanoseconds, !inclusive);
7120
+ if (index >= plan.count) {
7121
+ this.assertNumericCandidateReachable(this.numericExhaustionCandidate(plan));
7122
+ return {
7123
+ handled: true,
7124
+ value: null
7125
+ };
7126
+ }
7127
+ const candidate = plan.select(index);
7128
+ if (!candidate) return { handled: false };
7129
+ this.assertNumericCandidateReachable(candidate);
7130
+ return {
7131
+ handled: true,
7132
+ value: this.zdtFromEpochMs(candidate.epochMilliseconds)
7133
+ };
7134
+ }
7135
+ tryNumericPrevious(targetEpochNanoseconds, inclusive) {
7136
+ const plan = this.getNumericQueryPlan();
7137
+ if (!plan) return { handled: false };
7138
+ const stopIndex = plan.lowerBound(targetEpochNanoseconds, inclusive);
7139
+ const reachedCandidate = stopIndex < plan.count ? plan.select(stopIndex) : this.numericExhaustionCandidate(plan);
7140
+ this.assertNumericCandidateReachable(reachedCandidate);
7141
+ const resultIndex = stopIndex - 1;
7142
+ if (resultIndex < 0) return {
7143
+ handled: true,
7144
+ value: null
7145
+ };
7146
+ const candidate = plan.select(resultIndex);
7147
+ if (!candidate) return { handled: false };
7148
+ return {
7149
+ handled: true,
7150
+ value: this.zdtFromEpochMs(candidate.epochMilliseconds)
7151
+ };
7152
+ }
7153
+ tryNumericBetween(startEpochNanoseconds, endEpochNanoseconds, inclusive) {
7154
+ if (startEpochNanoseconds > endEpochNanoseconds) return { handled: false };
7155
+ const plan = this.getNumericQueryPlan();
7156
+ if (!plan) return { handled: false };
7157
+ const firstIndex = plan.lowerBound(startEpochNanoseconds, !inclusive);
7158
+ const endIndex = plan.lowerBound(endEpochNanoseconds, inclusive);
7159
+ const scanStopIndex = plan.lowerBound(endEpochNanoseconds, true);
7160
+ const reachedCandidate = scanStopIndex < plan.count ? plan.select(scanStopIndex) : this.numericExhaustionCandidate(plan);
7161
+ this.assertNumericCandidateReachable(reachedCandidate);
7162
+ if (firstIndex >= endIndex) return {
7163
+ handled: true,
7164
+ value: []
7165
+ };
7166
+ const dates = new Array(endIndex - firstIndex);
7167
+ for (let index = firstIndex; index < endIndex; index++) {
7168
+ const candidate = plan.select(index);
7169
+ if (!candidate) return { handled: false };
7170
+ dates[index - firstIndex] = this.zdtFromEpochMs(candidate.epochMilliseconds);
7171
+ }
7172
+ return {
7173
+ handled: true,
7174
+ value: dates
7175
+ };
7176
+ }
6698
7177
  /**
6699
7178
  * Returns all occurrences of the rule within a specified time window.
6700
7179
  * @param after - The start date or Temporal.ZonedDateTime object.
@@ -6705,6 +7184,8 @@ var RRuleTemporal = class RRuleTemporal {
6705
7184
  between(after, before, inc = false) {
6706
7185
  const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : normalizeZonedDateTime(after, "after").toInstant();
6707
7186
  const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : normalizeZonedDateTime(before, "before").toInstant();
7187
+ const numericResult = this.tryNumericBetween(startInst.epochNanoseconds, endInst.epochNanoseconds, inc);
7188
+ if (numericResult.handled) return RRuleTemporal.toPublicDates(numericResult.value);
6708
7189
  const startZdt = Temporal.Instant.from(startInst).toZonedDateTimeISO(this.tzid);
6709
7190
  const beforeZdt = Temporal.Instant.from(endInst).toZonedDateTimeISO(this.tzid);
6710
7191
  const tempOpts = { ...this.opts };
@@ -6816,6 +7297,8 @@ var RRuleTemporal = class RRuleTemporal {
6816
7297
  */
6817
7298
  next(after = /* @__PURE__ */ new Date(), inc = false) {
6818
7299
  const afterInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : normalizeZonedDateTime(after, "after").toInstant();
7300
+ const numericResult = this.tryNumericNext(afterInst.epochNanoseconds, inc);
7301
+ if (numericResult.handled) return RRuleTemporal.toPublicDate(numericResult.value);
6819
7302
  let result = null;
6820
7303
  const scanFrom = (rule) => {
6821
7304
  rule.allInternal((occ) => {
@@ -6853,6 +7336,8 @@ var RRuleTemporal = class RRuleTemporal {
6853
7336
  */
6854
7337
  previous(before = /* @__PURE__ */ new Date(), inc = false) {
6855
7338
  const beforeInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : normalizeZonedDateTime(before, "before").toInstant();
7339
+ const numericResult = this.tryNumericPrevious(beforeInst.epochNanoseconds, inc);
7340
+ if (numericResult.handled) return RRuleTemporal.toPublicDate(numericResult.value);
6856
7341
  const scanFrom = (rule) => {
6857
7342
  let prev = null;
6858
7343
  rule.allInternal((occ) => {