rrule-temporal 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3015 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
32
-
33
- // src/index.ts
34
- import { Temporal } from "@js-temporal/polyfill";
35
- var allowedFreq = ["YEARLY", "MONTHLY", "WEEKLY", "DAILY", "HOURLY", "MINUTELY", "SECONDLY"];
36
- var allowedWeekdays = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
37
- var weekdayToIsoDay = {
38
- MO: 1,
39
- TU: 2,
40
- WE: 3,
41
- TH: 4,
42
- FR: 5,
43
- SA: 6,
44
- SU: 7
45
- };
46
- var allowedFreqSet = new Set(allowedFreq);
47
- var allowedWeekdaysSet = new Set(allowedWeekdays);
48
- var byDayTokenRegex = new RegExp(`^([+-]?\\d{1,2})?(${allowedWeekdays.join("|")})$`);
49
- var byDayWeekdaySuffixRegex = new RegExp(`(${allowedWeekdays.join("|")})$`);
50
- var MS_PER_SECOND = 1e3;
51
- var MS_PER_MINUTE = 60 * MS_PER_SECOND;
52
- var MS_PER_HOUR = 60 * MS_PER_MINUTE;
53
- var MS_PER_DAY = 24 * MS_PER_HOUR;
54
- var MS_PER_WEEK = 7 * MS_PER_DAY;
55
- var GREGORIAN_MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
56
- var GREGORIAN_WEEKDAY_OFFSETS = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
57
- var NS_PER_MILLISECOND = BigInt(1e6);
58
- var NS_PER_SECOND = BigInt(1e9);
59
- var NS_PER_MINUTE = BigInt(60) * NS_PER_SECOND;
60
- var NS_PER_HOUR = BigInt(60) * NS_PER_MINUTE;
61
- var NS_PER_DAY = BigInt(24) * NS_PER_HOUR;
62
- var NS_PER_WEEK = BigInt(7) * NS_PER_DAY;
63
- function addIsoDays(dayOfWeek, deltaDays) {
64
- return (dayOfWeek - 1 + deltaDays % 7 + 7) % 7 + 1;
65
- }
66
- function extractWeekdayToken(token) {
67
- const m = token.toUpperCase().match(byDayWeekdaySuffixRegex);
68
- const weekday = m == null ? void 0 : m[1];
69
- if (!weekday || !allowedWeekdaysSet.has(weekday)) return null;
70
- return weekday;
71
- }
72
- function parseByDayToken(token) {
73
- const m = token.toUpperCase().match(byDayTokenRegex);
74
- if (!m) return null;
75
- const ord = m[1] ? parseInt(m[1], 10) : 0;
76
- const weekday = m[2];
77
- if (!weekday || !allowedWeekdaysSet.has(weekday)) return null;
78
- return { ord, weekday };
79
- }
80
- function isIcsOpts(opts) {
81
- return typeof opts.rruleString === "string";
82
- }
83
- function unfoldLine(foldedLine) {
84
- return foldedLine.replace(/\r?\n[ \t]/g, "");
85
- }
86
- function parseIcsDateTime(dateStr, tzid, valueType) {
87
- const isDate = valueType === "DATE" || !dateStr.includes("T");
88
- const isoDate = `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
89
- if (isDate) {
90
- return Temporal.PlainDate.from(isoDate).toZonedDateTime({ timeZone: tzid });
91
- }
92
- if (dateStr.endsWith("Z")) {
93
- const iso = `${isoDate}T${dateStr.slice(9, 15)}Z`;
94
- return Temporal.Instant.from(iso).toZonedDateTimeISO(tzid || "UTC");
95
- } else {
96
- const iso = `${isoDate}T${dateStr.slice(9)}`;
97
- return Temporal.PlainDateTime.from(iso).toZonedDateTime(tzid);
98
- }
99
- }
100
- function parseDateLines(lines, linePrefix, defaultTzid) {
101
- const dates = [];
102
- const regex = new RegExp(`^${linePrefix}(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)`, "i");
103
- for (const line of lines) {
104
- const match = line.match(regex);
105
- if (match) {
106
- const [, valueType, tzid, dateValuesStr] = match;
107
- const timezone = tzid || defaultTzid;
108
- const dateValues = dateValuesStr.split(",");
109
- dates.push(...dateValues.map((dateValue) => parseIcsDateTime(dateValue, timezone, valueType)));
110
- }
111
- }
112
- return dates;
113
- }
114
- function parseNumberArray(val, sort = false) {
115
- const arr = val.split(",").map((n) => parseInt(n, 10));
116
- if (sort) {
117
- return arr.sort((a, b) => a - b);
118
- }
119
- return arr;
120
- }
121
- function parseByMonthArray(val) {
122
- return val.split(",").map((tok) => {
123
- const t = tok.trim();
124
- if (/^\d+L$/i.test(t)) return t.toUpperCase();
125
- const n = parseInt(t, 10);
126
- return Number.isFinite(n) ? n : t;
127
- });
128
- }
129
- function parseRRuleString(input, targetTimezone, dtstart, strict = false) {
130
- var _a, _b, _c, _d, _e;
131
- const unfoldedInput = unfoldLine(input).trim();
132
- let parsedDtstart;
133
- let tzid = targetTimezone;
134
- let dtstartValueType = "DATE-TIME";
135
- let dtstartHasTzid = false;
136
- let dtstartIsUtc = false;
137
- let rruleLine;
138
- let exDate = [];
139
- let rDate = [];
140
- if (/^DTSTART/im.test(unfoldedInput)) {
141
- const lines = unfoldedInput.split(/\s+/);
142
- const dtLine = lines.find((line) => line.match(/^DTSTART/i));
143
- const rrLine = lines.find((line) => line.match(/^RRULE:/i));
144
- const exLines = lines.filter((line) => line.match(/^EXDATE/i));
145
- const rLines = lines.filter((line) => line.match(/^RDATE/i));
146
- const dtMatch = dtLine.match(/DTSTART(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)/i);
147
- if (!dtMatch) throw new Error("Invalid DTSTART in ICS snippet");
148
- const [, valueType, dtTzid, dtValue] = dtMatch;
149
- const normalizedValueType = (valueType || ((dtValue == null ? void 0 : dtValue.includes("T")) ? "DATE-TIME" : "DATE")).toUpperCase();
150
- dtstartValueType = normalizedValueType === "DATE" ? "DATE" : "DATE-TIME";
151
- dtstartHasTzid = Boolean(dtTzid);
152
- dtstartIsUtc = Boolean(dtValue == null ? void 0 : dtValue.endsWith("Z"));
153
- const effectiveTzid = (_b = (_a = dtTzid != null ? dtTzid : targetTimezone) != null ? _a : tzid) != null ? _b : "UTC";
154
- parsedDtstart = parseIcsDateTime(dtValue, effectiveTzid, dtstartValueType);
155
- tzid = (_e = (_d = (_c = dtTzid != null ? dtTzid : parsedDtstart.timeZoneId) != null ? _c : targetTimezone) != null ? _d : tzid) != null ? _e : "UTC";
156
- rruleLine = rrLine;
157
- exDate = parseDateLines(exLines, "EXDATE", tzid != null ? tzid : "UTC");
158
- rDate = parseDateLines(rLines, "RDATE", tzid != null ? tzid : "UTC");
159
- } else {
160
- parsedDtstart = dtstart;
161
- rruleLine = unfoldedInput;
162
- if (parsedDtstart) {
163
- tzid = parsedDtstart.timeZoneId;
164
- dtstartValueType = "DATE-TIME";
165
- dtstartHasTzid = true;
166
- dtstartIsUtc = parsedDtstart.timeZoneId === "UTC";
167
- }
168
- }
169
- const parts = rruleLine ? rruleLine.replace(/^RRULE:/i, "").split(";") : [];
170
- const opts = {
171
- dtstart: parsedDtstart,
172
- tzid,
173
- exDate: exDate.length > 0 ? exDate : void 0,
174
- rDate: rDate.length > 0 ? rDate : void 0
175
- };
176
- let pendingSkip;
177
- for (const part of parts) {
178
- const [key, val] = part.split("=");
179
- if (!key) continue;
180
- switch (key.toUpperCase()) {
181
- case "RSCALE":
182
- if (val) {
183
- opts.rscale = val.toUpperCase();
184
- if (pendingSkip && !opts.skip) {
185
- opts.skip = pendingSkip;
186
- pendingSkip = void 0;
187
- }
188
- }
189
- break;
190
- case "SKIP": {
191
- const v = (val || "").toUpperCase();
192
- if (!["OMIT", "BACKWARD", "FORWARD"].includes(v)) {
193
- throw new Error(`Invalid SKIP value: ${val}`);
194
- }
195
- if (opts.rscale) {
196
- opts.skip = v;
197
- } else {
198
- pendingSkip = v;
199
- }
200
- break;
201
- }
202
- case "FREQ":
203
- opts.freq = val.toUpperCase();
204
- break;
205
- case "INTERVAL":
206
- opts.interval = parseInt(val, 10);
207
- break;
208
- case "COUNT":
209
- opts.count = parseInt(val, 10);
210
- break;
211
- case "UNTIL": {
212
- const untilHasTime = val.includes("T");
213
- if (dtstartValueType === "DATE") {
214
- if (untilHasTime) {
215
- throw new Error("UNTIL rule part MUST have the same value type as DTSTART");
216
- }
217
- opts.until = parseIcsDateTime(val, tzid || "UTC", "DATE");
218
- break;
219
- }
220
- if (!untilHasTime) {
221
- if (strict) {
222
- throw new Error("UNTIL rule part MUST have the same value type as DTSTART");
223
- }
224
- const localEndOfDay = parseIcsDateTime(val, tzid || "UTC", "DATE").with({
225
- hour: 23,
226
- minute: 59,
227
- second: 59,
228
- millisecond: 0,
229
- microsecond: 0,
230
- nanosecond: 0
231
- });
232
- const requiresUtc2 = dtstartHasTzid || dtstartIsUtc;
233
- opts.until = requiresUtc2 ? localEndOfDay.withTimeZone("UTC") : localEndOfDay;
234
- break;
235
- }
236
- const requiresUtc = dtstartHasTzid || dtstartIsUtc;
237
- if (requiresUtc && !val.endsWith("Z")) {
238
- throw new Error("UNTIL rule part MUST always be specified as a date with UTC time");
239
- }
240
- opts.until = parseIcsDateTime(val, tzid || "UTC", "DATE-TIME");
241
- break;
242
- }
243
- case "BYHOUR":
244
- opts.byHour = parseNumberArray(val, true);
245
- break;
246
- case "BYMINUTE":
247
- opts.byMinute = parseNumberArray(val, true);
248
- break;
249
- case "BYSECOND":
250
- opts.bySecond = parseNumberArray(val, true);
251
- break;
252
- case "BYDAY":
253
- opts.byDay = val.split(",").map((token) => token.toUpperCase());
254
- break;
255
- case "BYMONTH":
256
- opts.byMonth = parseByMonthArray(val);
257
- break;
258
- case "BYMONTHDAY":
259
- opts.byMonthDay = parseNumberArray(val);
260
- break;
261
- case "BYYEARDAY":
262
- opts.byYearDay = parseNumberArray(val);
263
- break;
264
- case "BYWEEKNO":
265
- opts.byWeekNo = parseNumberArray(val);
266
- break;
267
- case "BYSETPOS":
268
- opts.bySetPos = parseNumberArray(val);
269
- break;
270
- case "WKST":
271
- opts.wkst = val == null ? void 0 : val.toUpperCase();
272
- break;
273
- }
274
- }
275
- if (pendingSkip && !opts.rscale) {
276
- throw new Error("SKIP MUST NOT be present unless RSCALE is present");
277
- }
278
- if (pendingSkip && opts.rscale && !opts.skip) {
279
- opts.skip = pendingSkip;
280
- }
281
- return opts;
282
- }
283
- var _RRuleTemporal = class _RRuleTemporal {
284
- /**
285
- * Normalize a ZonedDateTime to the polyfill implementation.
286
- * This prevents type mismatches when mixing native and polyfill Temporal objects.
287
- */
288
- static normalizeToPolyfill(zdt) {
289
- return Temporal.ZonedDateTime.from(zdt.toString());
290
- }
291
- constructor(params) {
292
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
293
- let manual;
294
- if (isIcsOpts(params)) {
295
- const parsed = parseRRuleString(params.rruleString, params.tzid, params.dtstart, (_a = params.strict) != null ? _a : false);
296
- if (!parsed.dtstart) {
297
- throw new Error("dtstart is required - provide it either in rruleString or as a separate parameter");
298
- }
299
- this.tzid = (_c = (_b = parsed.tzid) != null ? _b : params.tzid) != null ? _c : "UTC";
300
- this.originalDtstart = _RRuleTemporal.normalizeToPolyfill(parsed.dtstart);
301
- manual = __spreadProps(__spreadValues({}, parsed), {
302
- // Allow explicit COUNT/UNTIL overrides when omitted from the RRULE string
303
- count: (_d = params.count) != null ? _d : parsed.count,
304
- until: (_e = params.until) != null ? _e : parsed.until,
305
- strict: params.strict,
306
- maxIterations: params.maxIterations,
307
- includeDtstart: params.includeDtstart,
308
- tzid: this.tzid
309
- });
310
- } else {
311
- manual = __spreadValues({}, params);
312
- if (typeof manual.dtstart === "string") {
313
- throw new Error("Manual dtstart must be a ZonedDateTime");
314
- }
315
- manual.tzid = manual.tzid || manual.dtstart.timeZoneId;
316
- this.tzid = manual.tzid;
317
- this.originalDtstart = _RRuleTemporal.normalizeToPolyfill(manual.dtstart);
318
- }
319
- if (!manual.freq) throw new Error("RRULE must include FREQ");
320
- manual.interval = (_f = manual.interval) != null ? _f : 1;
321
- if (manual.interval <= 0) {
322
- throw new Error("Cannot create RRule: interval must be greater than 0");
323
- }
324
- if (manual.until && !(manual.until instanceof Temporal.ZonedDateTime)) {
325
- throw new Error("Manual until must be a ZonedDateTime");
326
- }
327
- if (manual.until) {
328
- manual.until = _RRuleTemporal.normalizeToPolyfill(manual.until);
329
- }
330
- this.opts = this.sanitizeOpts(manual);
331
- this.maxIterations = (_g = manual.maxIterations) != null ? _g : 1e4;
332
- this.includeDtstart = (_h = manual.includeDtstart) != null ? _h : false;
333
- this.parsedByDayTokens = this.buildParsedByDayTokens(this.opts.byDay);
334
- this.simpleByDayIsoDays = this.buildByDayIsoDays(this.parsedByDayTokens, false);
335
- this.allByDayIsoDays = this.buildByDayIsoDays(this.parsedByDayTokens, true);
336
- this.hasOrdinalByDay = (_j = (_i = this.parsedByDayTokens) == null ? void 0 : _i.some((token) => token.ord !== 0)) != null ? _j : false;
337
- this.canUseEpochMillisecondsPrecisionFlag = this.originalDtstart.microsecond === 0 && this.originalDtstart.nanosecond === 0 && (!this.opts.until || this.opts.until.microsecond === 0 && this.opts.until.nanosecond === 0);
338
- this.timeSlotOffsetsMs = this.buildTimeSlotOffsetsMs();
339
- this.numericByMonths = (_k = this.opts.byMonth) == null ? void 0 : _k.filter((value) => typeof value === "number");
340
- }
341
- buildParsedByDayTokens(byDay) {
342
- if (!(byDay == null ? void 0 : byDay.length)) return void 0;
343
- const tokens = byDay.map((tok) => {
344
- const parsed = parseByDayToken(tok);
345
- if (!parsed) return null;
346
- return {
347
- ord: parsed.ord,
348
- weekday: parsed.weekday,
349
- isoDay: weekdayToIsoDay[parsed.weekday]
350
- };
351
- }).filter((token) => token !== null);
352
- return tokens.length > 0 ? tokens : void 0;
353
- }
354
- buildByDayIsoDays(tokens, includeOrdinals) {
355
- if (!(tokens == null ? void 0 : tokens.length)) return void 0;
356
- const isoDays = tokens.filter((token) => includeOrdinals || token.ord === 0).map((token) => token.isoDay);
357
- if (!isoDays.length) return void 0;
358
- return [...new Set(isoDays)].sort((a, b) => a - b);
359
- }
360
- sanitizeNumericArray(arr, min, max, allowZero = false, sort = false) {
361
- if (!arr) return void 0;
362
- const sanitized = arr.filter((n) => Number.isInteger(n) && n >= min && n <= max && (allowZero || n !== 0));
363
- if (sanitized.length === 0) return void 0;
364
- return sort ? sanitized.sort((a, b) => a - b) : sanitized;
365
- }
366
- sanitizeByDay(byDay) {
367
- const days = (byDay != null ? byDay : []).filter((day) => Boolean(day) && typeof day === "string");
368
- const normalized = [];
369
- for (const day of days) {
370
- const token = day.toUpperCase();
371
- const parsed = parseByDayToken(token);
372
- if (!parsed) {
373
- throw new Error(`Invalid BYDAY value: ${day}`);
374
- }
375
- if (parsed.ord === 0 && /^[+-]?\d/.test(token)) {
376
- throw new Error(`Invalid BYDAY value: ${day}`);
377
- }
378
- normalized.push(token);
379
- }
380
- return normalized.length > 0 ? normalized : void 0;
381
- }
382
- enforceStrictRfc(opts) {
383
- var _a;
384
- if (!opts.strict) return;
385
- const freq = opts.freq;
386
- if (opts.byWeekNo && freq !== "YEARLY") {
387
- throw new Error("BYWEEKNO MUST NOT be used unless FREQ=YEARLY");
388
- }
389
- if (opts.byYearDay && ["DAILY", "WEEKLY", "MONTHLY"].includes(freq)) {
390
- throw new Error("BYYEARDAY MUST NOT be used when FREQ is DAILY, WEEKLY, or MONTHLY");
391
- }
392
- if (opts.byMonthDay && freq === "WEEKLY") {
393
- throw new Error("BYMONTHDAY MUST NOT be used when FREQ is WEEKLY");
394
- }
395
- const hasNumericByDay = ((_a = opts.byDay) != null ? _a : []).some((day) => /^[+-]?\d/.test(day));
396
- if (hasNumericByDay && !["MONTHLY", "YEARLY"].includes(freq)) {
397
- throw new Error("BYDAY with numeric value MUST NOT be used unless FREQ is MONTHLY or YEARLY");
398
- }
399
- if (hasNumericByDay && freq === "YEARLY" && opts.byWeekNo) {
400
- throw new Error("BYDAY with numeric value MUST NOT be used with FREQ=YEARLY when BYWEEKNO is present");
401
- }
402
- const hasOtherBy = Boolean(
403
- opts.byDay || opts.byMonth || opts.byMonthDay || opts.byYearDay || opts.byWeekNo || opts.byHour || opts.byMinute || opts.bySecond
404
- );
405
- if (opts.bySetPos && !hasOtherBy) {
406
- throw new Error("BYSETPOS MUST be used with another BYxxx rule part");
407
- }
408
- }
409
- sanitizeOpts(opts) {
410
- var _a;
411
- if (!allowedFreqSet.has(opts.freq)) {
412
- throw new Error(`Invalid FREQ value: ${opts.freq}`);
413
- }
414
- opts.byDay = this.sanitizeByDay(opts.byDay);
415
- if (opts.wkst) {
416
- const wkst = opts.wkst.toUpperCase();
417
- if (!allowedWeekdaysSet.has(wkst)) {
418
- throw new Error(`Invalid WKST value: ${opts.wkst}`);
419
- }
420
- opts.wkst = wkst;
421
- }
422
- if (opts.byMonth) {
423
- const numeric = opts.byMonth.filter((v) => typeof v === "number");
424
- const stringy = opts.byMonth.filter((v) => typeof v === "string");
425
- const sanitizedNum = (_a = this.sanitizeNumericArray(numeric, 1, 12, false, false)) != null ? _a : [];
426
- const merged = [...sanitizedNum, ...stringy];
427
- opts.byMonth = merged.length > 0 ? merged : void 0;
428
- }
429
- if (opts.rscale && !opts.skip) {
430
- opts.skip = "OMIT";
431
- }
432
- opts.byMonthDay = this.sanitizeNumericArray(opts.byMonthDay, -31, 31, false, false);
433
- opts.byYearDay = this.sanitizeNumericArray(opts.byYearDay, -366, 366, false, false);
434
- opts.byWeekNo = this.sanitizeNumericArray(opts.byWeekNo, -53, 53, false, false);
435
- opts.byHour = this.sanitizeNumericArray(opts.byHour, 0, 23, true, true);
436
- opts.byMinute = this.sanitizeNumericArray(opts.byMinute, 0, 59, true, true);
437
- opts.bySecond = this.sanitizeNumericArray(opts.bySecond, 0, 59, true, true);
438
- if (opts.bySetPos) {
439
- if (opts.bySetPos.some((p) => p === 0)) {
440
- throw new Error("bySetPos may not contain 0");
441
- }
442
- opts.bySetPos = this.sanitizeNumericArray(opts.bySetPos, -Infinity, Infinity, false, false);
443
- }
444
- this.enforceStrictRfc(opts);
445
- return opts;
446
- }
447
- rawAdvance(zdt) {
448
- const { freq, interval } = this.opts;
449
- switch (freq) {
450
- case "DAILY":
451
- return zdt.add({ days: interval });
452
- case "WEEKLY":
453
- return zdt.add({ weeks: interval });
454
- case "MONTHLY":
455
- return zdt.add({ months: interval });
456
- case "YEARLY":
457
- return zdt.add({ years: interval });
458
- case "HOURLY": {
459
- const originalHour = zdt.hour;
460
- let next = zdt.add({ hours: interval });
461
- if (next.hour === originalHour && interval === 1) {
462
- next = next.add({ hours: interval });
463
- }
464
- return next;
465
- }
466
- case "MINUTELY":
467
- return zdt.add({ minutes: interval });
468
- case "SECONDLY":
469
- return zdt.add({ seconds: interval });
470
- default:
471
- throw new Error(`Unsupported FREQ: ${freq}`);
472
- }
473
- }
474
- /** Expand one base ZonedDateTime into all BYHOUR × BYMINUTE × BYSECOND
475
- * combinations, keeping chronological order. If the options are not
476
- * present the original date is returned unchanged.
477
- */
478
- expandByTime(base) {
479
- var _a, _b, _c;
480
- if (!this.opts.byHour && !this.opts.byMinute && !this.opts.bySecond) {
481
- return [base];
482
- }
483
- const hours = (_a = this.opts.byHour) != null ? _a : [base.hour];
484
- const minutes = (_b = this.opts.byMinute) != null ? _b : [base.minute];
485
- const seconds = (_c = this.opts.bySecond) != null ? _c : [base.second];
486
- if (hours.length === 1 && minutes.length === 1 && seconds.length === 1) {
487
- const hour = hours[0];
488
- const minute = minutes[0];
489
- const second = seconds[0];
490
- if (hour === base.hour && minute === base.minute && second === base.second) {
491
- return [base];
492
- }
493
- return [base.with({ hour, minute, second })];
494
- }
495
- const out = [];
496
- for (const h of hours) {
497
- for (const m of minutes) {
498
- for (const s of seconds) {
499
- out.push(base.with({ hour: h, minute: m, second: s }));
500
- }
501
- }
502
- }
503
- return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
504
- }
505
- nextCandidateSameDate(zdt) {
506
- const { freq, interval = 1, byHour, byMinute, bySecond } = this.opts;
507
- if (freq === "HOURLY" && byHour && byHour.length === 1) {
508
- return this.applyTimeOverride(zdt.add({ days: interval }));
509
- }
510
- if (freq === "MINUTELY" && byMinute && byMinute.length === 1) {
511
- return this.applyTimeOverride(zdt.add({ hours: interval }));
512
- }
513
- if (bySecond && bySecond.length > 1) {
514
- const idx = bySecond.indexOf(zdt.second);
515
- if (idx !== -1 && idx < bySecond.length - 1) {
516
- return zdt.with({ second: bySecond[idx + 1] });
517
- }
518
- }
519
- if (freq === "MINUTELY" && byHour && byHour.length > 1 && !byMinute) {
520
- const next = zdt.add({ minutes: interval });
521
- if (byHour.includes(next.hour)) {
522
- return next.with({ second: bySecond ? bySecond[0] : zdt.second });
523
- }
524
- const nextHour = byHour.find((h) => h > zdt.hour) || byHour[0];
525
- if (nextHour && nextHour > zdt.hour) {
526
- return zdt.with({ hour: nextHour, minute: 0, second: bySecond ? bySecond[0] : zdt.second });
527
- }
528
- return this.applyTimeOverride(zdt.add({ days: 1 }));
529
- }
530
- if (freq === "SECONDLY") {
531
- let candidate = zdt;
532
- if (bySecond && bySecond.length > 0) {
533
- const nextSecondInList = bySecond.find((s) => s > candidate.second);
534
- if (nextSecondInList !== void 0) {
535
- return candidate.with({ second: nextSecondInList });
536
- }
537
- candidate = candidate.with({ second: bySecond[0] }).add({ minutes: 1 });
538
- } else {
539
- candidate = candidate.add({ seconds: interval });
540
- }
541
- if (byMinute && byMinute.length > 0) {
542
- if (!byMinute.includes(candidate.minute) || candidate.minute === zdt.minute && candidate.second < zdt.second) {
543
- const nextMinuteInList = byMinute.find((m) => m > candidate.minute);
544
- if (nextMinuteInList !== void 0) {
545
- return candidate.with({ minute: nextMinuteInList, second: bySecond ? bySecond[0] : 0 });
546
- }
547
- candidate = candidate.with({ minute: byMinute[0], second: bySecond ? bySecond[0] : 0 }).add({ hours: 1 });
548
- }
549
- }
550
- if (byHour && byHour.length > 0) {
551
- if (!byHour.includes(candidate.hour) || candidate.hour === zdt.hour && candidate.minute < zdt.minute) {
552
- const nextHourInList = byHour.find((h) => h > candidate.hour);
553
- if (nextHourInList !== void 0) {
554
- return candidate.with({
555
- hour: nextHourInList,
556
- minute: byMinute ? byMinute[0] : 0,
557
- second: bySecond ? bySecond[0] : 0
558
- });
559
- }
560
- candidate = candidate.with({ hour: byHour[0], minute: byMinute ? byMinute[0] : 0, second: bySecond ? bySecond[0] : 0 }).add({ days: 1 });
561
- }
562
- }
563
- return candidate;
564
- }
565
- if (byMinute && byMinute.length > 1) {
566
- const idx = byMinute.indexOf(zdt.minute);
567
- if (idx !== -1 && idx < byMinute.length - 1) {
568
- return zdt.with({
569
- minute: byMinute[idx + 1],
570
- second: bySecond ? bySecond[0] : zdt.second
571
- });
572
- }
573
- if (freq === "MINUTELY" && idx === byMinute.length - 1) {
574
- if (byHour && byHour.length > 0) {
575
- const currentHourIdx = byHour.indexOf(zdt.hour);
576
- if (currentHourIdx !== -1 && currentHourIdx < byHour.length - 1) {
577
- return zdt.with({
578
- hour: byHour[currentHourIdx + 1],
579
- minute: byMinute[0],
580
- second: bySecond ? bySecond[0] : zdt.second
581
- });
582
- } else {
583
- return this.applyTimeOverride(zdt.add({ days: 1 }));
584
- }
585
- }
586
- return zdt.add({ hours: interval }).with({
587
- minute: byMinute[0],
588
- second: bySecond ? bySecond[0] : zdt.second
589
- });
590
- }
591
- }
592
- if (byHour && byHour.length > 1) {
593
- const idx = byHour.indexOf(zdt.hour);
594
- if (idx !== -1 && idx < byHour.length - 1) {
595
- return zdt.with({
596
- hour: byHour[idx + 1],
597
- minute: byMinute ? byMinute[0] : zdt.minute,
598
- second: bySecond ? bySecond[0] : zdt.second
599
- });
600
- }
601
- }
602
- if (freq === "HOURLY" && byHour && byHour.length > 1) {
603
- return this.applyTimeOverride(zdt.add({ days: 1 }));
604
- }
605
- return this.applyTimeOverride(this.rawAdvance(zdt));
606
- }
607
- applyTimeOverride(zdt) {
608
- const { byHour, byMinute, bySecond } = this.opts;
609
- let dt = zdt;
610
- if (byHour) dt = dt.with({ hour: byHour[0] });
611
- if (byMinute) dt = dt.with({ minute: byMinute[0] });
612
- if (bySecond) dt = dt.with({ second: bySecond[0] });
613
- return dt;
614
- }
615
- computeFirst() {
616
- var _a, _b, _c, _d;
617
- let zdt = this.originalDtstart;
618
- if (((_a = this.opts.byWeekNo) == null ? void 0 : _a.length) && ["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq)) {
619
- let targetWeek = this.opts.byWeekNo[0];
620
- let targetYear = zdt.year;
621
- while (targetYear <= zdt.year + 10) {
622
- const jan1 = zdt.with({ year: targetYear, month: 1, day: 1 });
623
- const dec31 = zdt.with({ year: targetYear, month: 12, day: 31 });
624
- let hasTargetWeek = false;
625
- if (targetWeek > 0) {
626
- let maxWeek = 52;
627
- if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
628
- maxWeek = 53;
629
- }
630
- hasTargetWeek = targetWeek <= maxWeek;
631
- } else {
632
- let maxWeek = 52;
633
- if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
634
- maxWeek = 53;
635
- }
636
- hasTargetWeek = -targetWeek <= maxWeek;
637
- }
638
- if (hasTargetWeek) {
639
- const firstThursday = jan1.add({ days: (4 - jan1.dayOfWeek + 7) % 7 });
640
- let weekStart;
641
- if (targetWeek > 0) {
642
- weekStart = firstThursday.subtract({ days: 3 }).add({ weeks: targetWeek - 1 });
643
- } else {
644
- const lastWeek = jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4 ? 53 : 52;
645
- weekStart = firstThursday.subtract({ days: 3 }).add({ weeks: lastWeek + targetWeek });
646
- }
647
- if ((_b = this.opts.byDay) == null ? void 0 : _b.length) {
648
- const dayMap = weekdayToIsoDay;
649
- const targetDays = this.opts.byDay.map((tok) => extractWeekdayToken(tok)).filter((day) => day !== null).map((day) => dayMap[day]).filter(Boolean);
650
- if (targetDays.length) {
651
- const candidates = targetDays.map((dayOfWeek) => {
652
- const delta = (dayOfWeek - weekStart.dayOfWeek + 7) % 7;
653
- return weekStart.add({ days: delta });
654
- });
655
- const firstCandidate = candidates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b))[0];
656
- if (firstCandidate && Temporal.ZonedDateTime.compare(firstCandidate, this.originalDtstart) >= 0) {
657
- zdt = firstCandidate;
658
- break;
659
- }
660
- }
661
- } else {
662
- if (Temporal.ZonedDateTime.compare(weekStart, this.originalDtstart) >= 0) {
663
- zdt = weekStart;
664
- break;
665
- }
666
- }
667
- }
668
- targetYear++;
669
- }
670
- }
671
- if (((_c = this.opts.byDay) == null ? void 0 : _c.length) && !this.opts.byWeekNo) {
672
- const dayMap = weekdayToIsoDay;
673
- const hasOrdinalTokens = this.opts.byDay.some((tok) => /^[+-]?\d/.test(tok));
674
- if (hasOrdinalTokens && this.opts.byMonth && (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY")) {
675
- const months = this.opts.byMonth.filter((v) => typeof v === "number").sort((a, b) => a - b);
676
- let foundFirst = false;
677
- for (let year = zdt.year; year <= zdt.year + 10 && !foundFirst; year++) {
678
- for (const month of months) {
679
- if (year === zdt.year && month < zdt.month) continue;
680
- const monthSample = zdt.with({ year, month, day: 1 });
681
- const monthlyOccs = this.generateMonthlyOccurrences(monthSample);
682
- for (const occ of monthlyOccs) {
683
- if (Temporal.ZonedDateTime.compare(occ, zdt) >= 0) {
684
- if (!occ.toPlainDate().equals(zdt.toPlainDate())) {
685
- zdt = this.applyTimeOverride(occ.with({ hour: 0, minute: 0, second: 0 }));
686
- } else {
687
- zdt = occ;
688
- }
689
- foundFirst = true;
690
- break;
691
- }
692
- }
693
- if (foundFirst) break;
694
- }
695
- }
696
- } else {
697
- let deltas;
698
- const weekdayTokens = this.opts.byDay.map((tok) => extractWeekdayToken(tok)).filter((tok) => tok !== null);
699
- if (["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq) && weekdayTokens.length === this.opts.byDay.length) {
700
- deltas = weekdayTokens.map((tok) => (dayMap[tok] - zdt.dayOfWeek + 7) % 7);
701
- } else {
702
- deltas = weekdayTokens.map((wdTok) => (dayMap[wdTok] - zdt.dayOfWeek + 7) % 7);
703
- }
704
- if (deltas.length) {
705
- zdt = zdt.add({ days: Math.min(...deltas) });
706
- }
707
- }
708
- }
709
- const { byHour, byMinute, bySecond } = this.opts;
710
- if (this.opts.freq === "HOURLY" && !byHour && Temporal.ZonedDateTime.compare(
711
- zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
712
- this.originalDtstart
713
- ) > 0) {
714
- zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
715
- }
716
- if (this.opts.freq === "MINUTELY" && !byMinute && Temporal.ZonedDateTime.compare(
717
- zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
718
- this.originalDtstart
719
- ) > 0) {
720
- zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
721
- }
722
- if (this.opts.freq === "SECONDLY" && ((_d = this.opts.byWeekNo) == null ? void 0 : _d.length) && !bySecond && Temporal.ZonedDateTime.compare(
723
- zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
724
- this.originalDtstart
725
- ) > 0) {
726
- zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
727
- }
728
- if (byHour || byMinute || bySecond) {
729
- const candidates = this.expandByTime(zdt);
730
- for (const candidate of candidates) {
731
- if (Temporal.ZonedDateTime.compare(candidate, this.originalDtstart) >= 0) {
732
- return candidate;
733
- }
734
- }
735
- zdt = this.applyTimeOverride(this.rawAdvance(zdt));
736
- }
737
- return zdt;
738
- }
739
- // --- NEW: constraint checks ---
740
- // 2) Replace your matchesByDay with this:
741
- matchesByDay(zdt) {
742
- var _a, _b, _c;
743
- const { byDay, freq } = this.opts;
744
- if (!byDay) return true;
745
- if (!this.hasOrdinalByDay) {
746
- return (_b = (_a = this.simpleByDayIsoDays) == null ? void 0 : _a.includes(zdt.dayOfWeek)) != null ? _b : false;
747
- }
748
- for (const token of (_c = this.parsedByDayTokens) != null ? _c : []) {
749
- if (freq === "DAILY" && zdt.dayOfWeek === token.isoDay) return true;
750
- if (token.ord === 0) {
751
- if (zdt.dayOfWeek === token.isoDay) return true;
752
- continue;
753
- }
754
- const month = zdt.month;
755
- let dt = zdt.with({ day: 1 });
756
- const candidates = [];
757
- while (dt.month === month) {
758
- if (dt.dayOfWeek === token.isoDay) candidates.push(dt.day);
759
- dt = dt.add({ days: 1 });
760
- }
761
- const idx = token.ord > 0 ? token.ord - 1 : candidates.length + token.ord;
762
- if (candidates[idx] === zdt.day) return true;
763
- }
764
- return false;
765
- }
766
- matchesByMonth(zdt) {
767
- const { byMonth } = this.opts;
768
- if (!byMonth) return true;
769
- const nums = byMonth.filter((v) => typeof v === "number");
770
- if (nums.length === 0) return true;
771
- return nums.includes(zdt.month);
772
- }
773
- matchesNumericConstraint(value, constraints, maxPositiveValue) {
774
- return constraints.some((c) => {
775
- const target = c > 0 ? c : maxPositiveValue + c + 1;
776
- return value === target;
777
- });
778
- }
779
- matchesByMonthDay(zdt) {
780
- const { byMonthDay } = this.opts;
781
- if (!byMonthDay) return true;
782
- const lastDay = zdt.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
783
- return this.matchesNumericConstraint(zdt.day, byMonthDay, lastDay);
784
- }
785
- matchesByHour(zdt) {
786
- const { byHour } = this.opts;
787
- if (!byHour) return true;
788
- if (byHour.includes(zdt.hour)) {
789
- return true;
790
- }
791
- for (const h of byHour) {
792
- const intendedTime = zdt.with({ hour: h });
793
- if (intendedTime.hour === zdt.hour) {
794
- return true;
795
- }
796
- }
797
- return false;
798
- }
799
- matchesByMinute(zdt) {
800
- const { byMinute } = this.opts;
801
- if (!byMinute) return true;
802
- return byMinute.includes(zdt.minute);
803
- }
804
- matchesBySecond(zdt) {
805
- const { bySecond } = this.opts;
806
- if (!bySecond) return true;
807
- return bySecond.includes(zdt.second);
808
- }
809
- matchesAll(zdt) {
810
- 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);
811
- }
812
- matchesByYearDay(zdt) {
813
- const { byYearDay } = this.opts;
814
- if (!byYearDay) return true;
815
- const dayOfYear = zdt.dayOfYear;
816
- const last = zdt.with({ month: 12, day: 31 }).dayOfYear;
817
- return this.matchesNumericConstraint(dayOfYear, byYearDay, last);
818
- }
819
- getIsoWeekInfo(zdt) {
820
- const thursday = zdt.add({ days: 4 - zdt.dayOfWeek });
821
- const year = thursday.year;
822
- const jan1 = zdt.with({ year, month: 1, day: 1 });
823
- const firstThursday = jan1.add({ days: (4 - jan1.dayOfWeek + 7) % 7 });
824
- const diffDays = thursday.toPlainDate().since(firstThursday.toPlainDate()).days;
825
- const week = Math.floor(diffDays / 7) + 1;
826
- return { week, year };
827
- }
828
- matchesByWeekNo(zdt) {
829
- const { byWeekNo } = this.opts;
830
- if (!byWeekNo) return true;
831
- const { week, year } = this.getIsoWeekInfo(zdt);
832
- const jan1 = zdt.with({ year, month: 1, day: 1 });
833
- const isLeapYear = jan1.inLeapYear;
834
- const lastWeek = jan1.dayOfWeek === 4 || isLeapYear && jan1.dayOfWeek === 3 ? 53 : 52;
835
- return byWeekNo.some((wn) => {
836
- if (wn > 0) {
837
- return week === wn;
838
- } else {
839
- return week === lastWeek + wn + 1;
840
- }
841
- });
842
- }
843
- options() {
844
- return this.opts;
845
- }
846
- cloneOptions() {
847
- const _a = this.opts, {
848
- byHour,
849
- byMinute,
850
- bySecond,
851
- byDay,
852
- byMonth,
853
- byMonthDay,
854
- byYearDay,
855
- byWeekNo,
856
- bySetPos,
857
- rDate,
858
- exDate
859
- } = _a, rest = __objRest(_a, [
860
- "byHour",
861
- "byMinute",
862
- "bySecond",
863
- "byDay",
864
- "byMonth",
865
- "byMonthDay",
866
- "byYearDay",
867
- "byWeekNo",
868
- "bySetPos",
869
- "rDate",
870
- "exDate"
871
- ]);
872
- return __spreadProps(__spreadValues({}, rest), {
873
- byHour: byHour ? [...byHour] : void 0,
874
- byMinute: byMinute ? [...byMinute] : void 0,
875
- bySecond: bySecond ? [...bySecond] : void 0,
876
- byDay: byDay ? [...byDay] : void 0,
877
- byMonth: byMonth ? [...byMonth] : void 0,
878
- byMonthDay: byMonthDay ? [...byMonthDay] : void 0,
879
- byYearDay: byYearDay ? [...byYearDay] : void 0,
880
- byWeekNo: byWeekNo ? [...byWeekNo] : void 0,
881
- bySetPos: bySetPos ? [...bySetPos] : void 0,
882
- rDate: rDate ? [...rDate] : void 0,
883
- exDate: exDate ? [...exDate] : void 0
884
- });
885
- }
886
- cloneUpdateOptions(updates) {
887
- const cloned = {};
888
- if (Object.prototype.hasOwnProperty.call(updates, "byHour")) {
889
- cloned.byHour = Array.isArray(updates.byHour) ? [...updates.byHour] : updates.byHour;
890
- }
891
- if (Object.prototype.hasOwnProperty.call(updates, "byMinute")) {
892
- cloned.byMinute = Array.isArray(updates.byMinute) ? [...updates.byMinute] : updates.byMinute;
893
- }
894
- if (Object.prototype.hasOwnProperty.call(updates, "bySecond")) {
895
- cloned.bySecond = Array.isArray(updates.bySecond) ? [...updates.bySecond] : updates.bySecond;
896
- }
897
- if (Object.prototype.hasOwnProperty.call(updates, "byDay")) {
898
- cloned.byDay = Array.isArray(updates.byDay) ? [...updates.byDay] : updates.byDay;
899
- }
900
- if (Object.prototype.hasOwnProperty.call(updates, "byMonth")) {
901
- cloned.byMonth = Array.isArray(updates.byMonth) ? [...updates.byMonth] : updates.byMonth;
902
- }
903
- if (Object.prototype.hasOwnProperty.call(updates, "byMonthDay")) {
904
- cloned.byMonthDay = Array.isArray(updates.byMonthDay) ? [...updates.byMonthDay] : updates.byMonthDay;
905
- }
906
- if (Object.prototype.hasOwnProperty.call(updates, "byYearDay")) {
907
- cloned.byYearDay = Array.isArray(updates.byYearDay) ? [...updates.byYearDay] : updates.byYearDay;
908
- }
909
- if (Object.prototype.hasOwnProperty.call(updates, "byWeekNo")) {
910
- cloned.byWeekNo = Array.isArray(updates.byWeekNo) ? [...updates.byWeekNo] : updates.byWeekNo;
911
- }
912
- if (Object.prototype.hasOwnProperty.call(updates, "bySetPos")) {
913
- cloned.bySetPos = Array.isArray(updates.bySetPos) ? [...updates.bySetPos] : updates.bySetPos;
914
- }
915
- if (Object.prototype.hasOwnProperty.call(updates, "rDate")) {
916
- cloned.rDate = Array.isArray(updates.rDate) ? [...updates.rDate] : updates.rDate;
917
- }
918
- if (Object.prototype.hasOwnProperty.call(updates, "exDate")) {
919
- cloned.exDate = Array.isArray(updates.exDate) ? [...updates.exDate] : updates.exDate;
920
- }
921
- return cloned;
922
- }
923
- /**
924
- * Create a new {@link RRuleTemporal} instance with modified options while keeping the current one unchanged.
925
- *
926
- * @example
927
- * ```ts
928
- * const updated = rule.with({byMonthDay: [3]});
929
- * ```
930
- */
931
- with(updates) {
932
- var _a, _b;
933
- const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, this.cloneOptions()), updates), this.cloneUpdateOptions(updates)), {
934
- tzid: (_a = updates.tzid) != null ? _a : this.opts.tzid,
935
- dtstart: (_b = updates.dtstart) != null ? _b : this.opts.dtstart
936
- });
937
- return new _RRuleTemporal(merged);
938
- }
939
- addDtstartIfNeeded(dates, iterator) {
940
- if (this.includeDtstart && !this.matchesAll(this.originalDtstart)) {
941
- if (iterator && this.isExcluded(this.originalDtstart)) {
942
- return true;
943
- }
944
- if (iterator && !iterator(this.originalDtstart, dates.length)) {
945
- return false;
946
- }
947
- dates.push(this.originalDtstart);
948
- if (this.shouldBreakForCountLimit(dates.length)) {
949
- return false;
950
- }
951
- }
952
- return true;
953
- }
954
- canUseUtcLinearFastPath(iterator) {
955
- if (iterator || this.tzid !== "UTC" || this.opts.rscale || this.opts.rDate || this.opts.exDate) {
956
- return false;
957
- }
958
- if (this.opts.byMonth || this.opts.byMonthDay || this.opts.byYearDay || this.opts.byWeekNo || this.opts.bySetPos) {
959
- return false;
960
- }
961
- switch (this.opts.freq) {
962
- case "DAILY":
963
- return !this.opts.byHour && !this.opts.byMinute && !this.opts.bySecond && !this.hasOrdinalByDay;
964
- case "HOURLY":
965
- case "MINUTELY":
966
- return !this.opts.byDay && !this.opts.byHour && !this.opts.byMinute && !this.opts.bySecond;
967
- default:
968
- return false;
969
- }
970
- }
971
- canUseUtcWeeklyFastPath(iterator) {
972
- return !iterator && this.tzid === "UTC" && this.opts.freq === "WEEKLY" && !this.opts.rscale && !this.opts.rDate && !this.opts.exDate && !this.opts.byMonth && !this.opts.byMonthDay && !this.opts.byYearDay && !this.opts.byWeekNo && !this.opts.bySetPos && !this.opts.byHour && !this.opts.byMinute && !this.opts.bySecond && !this.hasOrdinalByDay;
973
- }
974
- canUseUtcMonthlyFastPath(iterator) {
975
- return !iterator && this.tzid === "UTC" && this.opts.freq === "MONTHLY" && !this.opts.rscale && !this.opts.rDate && !this.opts.exDate && !this.opts.byYearDay && !this.opts.byWeekNo && this.canUseEpochMillisecondsPrecisionFlag && !!(this.opts.byDay || this.opts.byMonthDay);
976
- }
977
- utcZdtFromEpochNanoseconds(epochNanoseconds) {
978
- return Temporal.Instant.fromEpochNanoseconds(epochNanoseconds).toZonedDateTimeISO("UTC");
979
- }
980
- utcZdtFromEpochMilliseconds(epochMilliseconds) {
981
- return Temporal.Instant.fromEpochMilliseconds(epochMilliseconds).toZonedDateTimeISO("UTC");
982
- }
983
- canUseUtcEpochMillisecondsPrecision() {
984
- return this.canUseEpochMillisecondsPrecisionFlag;
985
- }
986
- buildTimeSlotOffsetsMs() {
987
- var _a, _b, _c;
988
- if (!this.canUseEpochMillisecondsPrecisionFlag) return void 0;
989
- const hours = (_a = this.opts.byHour) != null ? _a : [this.originalDtstart.hour];
990
- const minutes = (_b = this.opts.byMinute) != null ? _b : [this.originalDtstart.minute];
991
- const seconds = (_c = this.opts.bySecond) != null ? _c : [this.originalDtstart.second];
992
- const baseMilliseconds = this.originalDtstart.millisecond;
993
- const offsets = [];
994
- for (const hour of hours) {
995
- for (const minute of minutes) {
996
- for (const second of seconds) {
997
- offsets.push(((hour * 60 + minute) * 60 + second) * MS_PER_SECOND + baseMilliseconds);
998
- }
999
- }
1000
- }
1001
- return offsets;
1002
- }
1003
- findFirstMatchingDailyStep(startDayOfWeek, stepDays, allowedDays) {
1004
- let dayOfWeek = startDayOfWeek;
1005
- for (let steps = 0; steps < 7; steps++) {
1006
- if (allowedDays.includes(dayOfWeek)) {
1007
- return steps;
1008
- }
1009
- dayOfWeek = addIsoDays(dayOfWeek, stepDays);
1010
- }
1011
- return null;
1012
- }
1013
- allUtcFastPath(iterator) {
1014
- if (this.canUseUtcLinearFastPath(iterator)) {
1015
- switch (this.opts.freq) {
1016
- case "DAILY":
1017
- return this._allUtcDailySimple();
1018
- case "HOURLY":
1019
- return this._allUtcFixedStepSimple(NS_PER_HOUR * BigInt(this.opts.interval));
1020
- case "MINUTELY":
1021
- return this._allUtcFixedStepSimple(NS_PER_MINUTE * BigInt(this.opts.interval));
1022
- }
1023
- }
1024
- if (this.canUseUtcMonthlyFastPath(iterator)) {
1025
- return this._allUtcMonthlyByDayOrMonthDay();
1026
- }
1027
- if (this.canUseUtcWeeklyFastPath(iterator)) {
1028
- return this._allUtcWeeklySimple();
1029
- }
1030
- return null;
1031
- }
1032
- _allUtcFixedStepSimple(stepNanoseconds) {
1033
- var _a, _b;
1034
- const dates = [];
1035
- if (!this.addDtstartIfNeeded(dates)) {
1036
- return dates;
1037
- }
1038
- let iterationCount = 0;
1039
- if (this.canUseUtcEpochMillisecondsPrecision()) {
1040
- let currentMilliseconds = this.originalDtstart.epochMilliseconds;
1041
- const stepMilliseconds = Number(stepNanoseconds / NS_PER_MILLISECOND);
1042
- const untilMilliseconds = (_a = this.opts.until) == null ? void 0 : _a.epochMilliseconds;
1043
- while (true) {
1044
- if (++iterationCount > this.maxIterations) {
1045
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1046
- }
1047
- if (untilMilliseconds !== void 0 && currentMilliseconds > untilMilliseconds) {
1048
- break;
1049
- }
1050
- dates.push(this.utcZdtFromEpochMilliseconds(currentMilliseconds));
1051
- if (this.shouldBreakForCountLimit(dates.length)) {
1052
- break;
1053
- }
1054
- currentMilliseconds += stepMilliseconds;
1055
- }
1056
- return dates;
1057
- }
1058
- let currentNanoseconds = this.originalDtstart.epochNanoseconds;
1059
- const untilNanoseconds = (_b = this.opts.until) == null ? void 0 : _b.epochNanoseconds;
1060
- while (true) {
1061
- if (++iterationCount > this.maxIterations) {
1062
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1063
- }
1064
- if (untilNanoseconds !== void 0 && currentNanoseconds > untilNanoseconds) {
1065
- break;
1066
- }
1067
- dates.push(this.utcZdtFromEpochNanoseconds(currentNanoseconds));
1068
- if (this.shouldBreakForCountLimit(dates.length)) {
1069
- break;
1070
- }
1071
- currentNanoseconds += stepNanoseconds;
1072
- }
1073
- return dates;
1074
- }
1075
- _allUtcDailySimple() {
1076
- var _a, _b;
1077
- const dates = [];
1078
- if (!this.addDtstartIfNeeded(dates)) {
1079
- return dates;
1080
- }
1081
- const stepDays = this.opts.interval;
1082
- const allowedDays = this.simpleByDayIsoDays;
1083
- let iterationCount = 0;
1084
- if (this.canUseUtcEpochMillisecondsPrecision()) {
1085
- const stepMilliseconds = stepDays * MS_PER_DAY;
1086
- const untilMilliseconds = (_a = this.opts.until) == null ? void 0 : _a.epochMilliseconds;
1087
- let currentMilliseconds = this.originalDtstart.epochMilliseconds;
1088
- let currentDayOfWeek2 = this.originalDtstart.dayOfWeek;
1089
- if (allowedDays == null ? void 0 : allowedDays.length) {
1090
- const firstMatchingStep = this.findFirstMatchingDailyStep(currentDayOfWeek2, stepDays, allowedDays);
1091
- if (firstMatchingStep === null) {
1092
- return dates;
1093
- }
1094
- currentMilliseconds += firstMatchingStep * stepMilliseconds;
1095
- currentDayOfWeek2 = addIsoDays(currentDayOfWeek2, firstMatchingStep * stepDays);
1096
- }
1097
- while (true) {
1098
- if (++iterationCount > this.maxIterations) {
1099
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1100
- }
1101
- if (untilMilliseconds !== void 0 && currentMilliseconds > untilMilliseconds) {
1102
- break;
1103
- }
1104
- if (!allowedDays || allowedDays.includes(currentDayOfWeek2)) {
1105
- dates.push(this.utcZdtFromEpochMilliseconds(currentMilliseconds));
1106
- if (this.shouldBreakForCountLimit(dates.length)) {
1107
- break;
1108
- }
1109
- }
1110
- currentMilliseconds += stepMilliseconds;
1111
- currentDayOfWeek2 = addIsoDays(currentDayOfWeek2, stepDays);
1112
- }
1113
- return dates;
1114
- }
1115
- const stepNanoseconds = BigInt(stepDays) * NS_PER_DAY;
1116
- const untilNanoseconds = (_b = this.opts.until) == null ? void 0 : _b.epochNanoseconds;
1117
- let currentNanoseconds = this.originalDtstart.epochNanoseconds;
1118
- let currentDayOfWeek = this.originalDtstart.dayOfWeek;
1119
- if (allowedDays == null ? void 0 : allowedDays.length) {
1120
- const firstMatchingStep = this.findFirstMatchingDailyStep(currentDayOfWeek, stepDays, allowedDays);
1121
- if (firstMatchingStep === null) {
1122
- return dates;
1123
- }
1124
- currentNanoseconds += BigInt(firstMatchingStep) * stepNanoseconds;
1125
- currentDayOfWeek = addIsoDays(currentDayOfWeek, firstMatchingStep * stepDays);
1126
- }
1127
- while (true) {
1128
- if (++iterationCount > this.maxIterations) {
1129
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1130
- }
1131
- if (untilNanoseconds !== void 0 && currentNanoseconds > untilNanoseconds) {
1132
- break;
1133
- }
1134
- if (!allowedDays || allowedDays.includes(currentDayOfWeek)) {
1135
- dates.push(this.utcZdtFromEpochNanoseconds(currentNanoseconds));
1136
- if (this.shouldBreakForCountLimit(dates.length)) {
1137
- break;
1138
- }
1139
- }
1140
- currentNanoseconds += stepNanoseconds;
1141
- currentDayOfWeek = addIsoDays(currentDayOfWeek, stepDays);
1142
- }
1143
- return dates;
1144
- }
1145
- _allUtcWeeklySimple() {
1146
- var _a, _b, _c, _d, _e;
1147
- const dates = [];
1148
- if (!this.addDtstartIfNeeded(dates)) {
1149
- return dates;
1150
- }
1151
- const start = this.originalDtstart;
1152
- const wkstToken = (_a = extractWeekdayToken(this.opts.wkst || "MO")) != null ? _a : "MO";
1153
- const wkstDay = (_b = weekdayToIsoDay[wkstToken]) != null ? _b : 1;
1154
- const targetDays = this.opts.byDay ? [...(_c = this.allByDayIsoDays) != null ? _c : []] : [start.dayOfWeek];
1155
- const dayOffsets = targetDays.map((day) => (day - wkstDay + 7) % 7).sort((a, b) => a - b);
1156
- const weekStartOffset = (start.dayOfWeek - wkstDay + 7) % 7;
1157
- let iterationCount = 0;
1158
- if (this.canUseUtcEpochMillisecondsPrecision()) {
1159
- const startMilliseconds = start.epochMilliseconds;
1160
- const untilMilliseconds = (_d = this.opts.until) == null ? void 0 : _d.epochMilliseconds;
1161
- const weekStepMilliseconds = this.opts.interval * MS_PER_WEEK;
1162
- let weekStartMilliseconds = startMilliseconds - weekStartOffset * MS_PER_DAY;
1163
- while (true) {
1164
- if (++iterationCount > this.maxIterations) {
1165
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1166
- }
1167
- for (const dayOffset of dayOffsets) {
1168
- const occurrenceMilliseconds = weekStartMilliseconds + dayOffset * MS_PER_DAY;
1169
- if (occurrenceMilliseconds < startMilliseconds) {
1170
- continue;
1171
- }
1172
- if (untilMilliseconds !== void 0 && occurrenceMilliseconds > untilMilliseconds) {
1173
- return dates;
1174
- }
1175
- dates.push(this.utcZdtFromEpochMilliseconds(occurrenceMilliseconds));
1176
- if (this.shouldBreakForCountLimit(dates.length)) {
1177
- return dates;
1178
- }
1179
- }
1180
- weekStartMilliseconds += weekStepMilliseconds;
1181
- }
1182
- }
1183
- const startNanoseconds = start.epochNanoseconds;
1184
- const untilNanoseconds = (_e = this.opts.until) == null ? void 0 : _e.epochNanoseconds;
1185
- const weekStepNanoseconds = BigInt(this.opts.interval) * NS_PER_WEEK;
1186
- let weekStartNanoseconds = startNanoseconds - BigInt(weekStartOffset) * NS_PER_DAY;
1187
- while (true) {
1188
- if (++iterationCount > this.maxIterations) {
1189
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1190
- }
1191
- for (const dayOffset of dayOffsets) {
1192
- const occurrenceNanoseconds = weekStartNanoseconds + BigInt(dayOffset) * NS_PER_DAY;
1193
- if (occurrenceNanoseconds < startNanoseconds) {
1194
- continue;
1195
- }
1196
- if (untilNanoseconds !== void 0 && occurrenceNanoseconds > untilNanoseconds) {
1197
- return dates;
1198
- }
1199
- dates.push(this.utcZdtFromEpochNanoseconds(occurrenceNanoseconds));
1200
- if (this.shouldBreakForCountLimit(dates.length)) {
1201
- return dates;
1202
- }
1203
- }
1204
- weekStartNanoseconds += weekStepNanoseconds;
1205
- }
1206
- }
1207
- hasSingleExpandedTimeSlot() {
1208
- var _a, _b, _c;
1209
- if (this.timeSlotOffsetsMs) {
1210
- return this.timeSlotOffsetsMs.length === 1;
1211
- }
1212
- const hours = (_a = this.opts.byHour) != null ? _a : [this.originalDtstart.hour];
1213
- const minutes = (_b = this.opts.byMinute) != null ? _b : [this.originalDtstart.minute];
1214
- const seconds = (_c = this.opts.bySecond) != null ? _c : [this.originalDtstart.second];
1215
- return hours.length === 1 && minutes.length === 1 && seconds.length === 1;
1216
- }
1217
- buildMonthlyOccurrenceOnDay(monthStart, day) {
1218
- const base = monthStart.day === day ? monthStart : monthStart.with({ day });
1219
- return this.applyTimeOverride(base);
1220
- }
1221
- applyBySetPosToSortedList(list) {
1222
- const { bySetPos } = this.opts;
1223
- if (!bySetPos || !bySetPos.length || list.length === 0) return list;
1224
- const out = [];
1225
- const len = list.length;
1226
- for (const pos of bySetPos) {
1227
- const idx = pos > 0 ? pos - 1 : len + pos;
1228
- if (idx >= 0 && idx < len) out.push(list[idx]);
1229
- }
1230
- return out;
1231
- }
1232
- generateMonthlyOccurrenceDays(sample) {
1233
- const { byDay, byMonth, byMonthDay } = this.opts;
1234
- const monthStart = sample.day === 1 ? sample : sample.with({ day: 1 });
1235
- if (byMonth && !byMonth.includes(sample.month)) return [];
1236
- const lastDay = monthStart.add({ months: 1 }).subtract({ days: 1 }).day;
1237
- let byMonthDayHits = [];
1238
- if (byMonthDay && byMonthDay.length > 0) {
1239
- byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
1240
- byMonthDayHits = [...new Set(byMonthDayHits)].sort((a, b) => a - b);
1241
- }
1242
- if (!byDay && byMonthDay && byMonthDay.length > 0) {
1243
- return byMonthDayHits;
1244
- }
1245
- if (!byDay) {
1246
- return [sample.day];
1247
- }
1248
- const tokens = this.parsedByDayTokens;
1249
- if (!(tokens == null ? void 0 : tokens.length)) return [];
1250
- const firstDayOfWeek = monthStart.dayOfWeek;
1251
- const lastDayOfWeek = (firstDayOfWeek - 1 + lastDay - 1) % 7 + 1;
1252
- const byDayHits = /* @__PURE__ */ new Set();
1253
- for (const { ord, isoDay } of tokens) {
1254
- if (ord === 0) {
1255
- let day = 1 + (isoDay - firstDayOfWeek + 7) % 7;
1256
- while (day <= lastDay) {
1257
- byDayHits.add(day);
1258
- day += 7;
1259
- }
1260
- } else {
1261
- let day;
1262
- if (ord > 0) {
1263
- day = 1 + (isoDay - firstDayOfWeek + 7) % 7 + 7 * (ord - 1);
1264
- } else {
1265
- const lastMatch = lastDay - (lastDayOfWeek - isoDay + 7) % 7;
1266
- day = lastMatch + 7 * (ord + 1);
1267
- }
1268
- if (day >= 1 && day <= lastDay) {
1269
- byDayHits.add(day);
1270
- }
1271
- }
1272
- }
1273
- let finalDays = [...byDayHits].sort((a, b) => a - b);
1274
- if (byMonthDay && byMonthDay.length > 0) {
1275
- if (byMonthDayHits.length === 0) {
1276
- return [];
1277
- }
1278
- const byMonthDayHitSet = new Set(byMonthDayHits);
1279
- finalDays = finalDays.filter((d) => byMonthDayHitSet.has(d));
1280
- }
1281
- return finalDays;
1282
- }
1283
- generateMonthlyOccurrencesOptimizedBySetPos(sample) {
1284
- if (!this.opts.bySetPos || !this.hasSingleExpandedTimeSlot()) {
1285
- return null;
1286
- }
1287
- const monthStart = sample.day === 1 ? sample : sample.with({ day: 1 });
1288
- const days = this.generateMonthlyOccurrenceDays(monthStart);
1289
- if (days.length === 0) {
1290
- return [];
1291
- }
1292
- const selectedDays = this.applyBySetPosToSortedList(days);
1293
- if (selectedDays.length === 0) {
1294
- return [];
1295
- }
1296
- return selectedDays.sort((a, b) => a - b).map((day) => this.buildMonthlyOccurrenceOnDay(monthStart, day));
1297
- }
1298
- isGregorianLeapYear(year) {
1299
- return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1300
- }
1301
- daysInGregorianMonth(year, month) {
1302
- if (month === 2 && this.isGregorianLeapYear(year)) {
1303
- return 29;
1304
- }
1305
- return GREGORIAN_MONTH_LENGTHS[month - 1];
1306
- }
1307
- gregorianIsoDayOfWeek(year, month, day) {
1308
- let adjustedYear = year;
1309
- if (month < 3) adjustedYear -= 1;
1310
- const sundayZero = (adjustedYear + Math.floor(adjustedYear / 4) - Math.floor(adjustedYear / 100) + Math.floor(adjustedYear / 400) + GREGORIAN_WEEKDAY_OFFSETS[month - 1] + day) % 7;
1311
- return sundayZero === 0 ? 7 : sundayZero;
1312
- }
1313
- monthIndexToYearMonth(monthIndex) {
1314
- const year = Math.floor(monthIndex / 12);
1315
- return {
1316
- year,
1317
- month: monthIndex - year * 12 + 1
1318
- };
1319
- }
1320
- generateMonthlyOccurrenceDaysUtc(year, month) {
1321
- if (this.numericByMonths && this.numericByMonths.length > 0 && !this.numericByMonths.includes(month)) {
1322
- return [];
1323
- }
1324
- const byMonthDay = this.opts.byMonthDay;
1325
- const byDay = this.opts.byDay;
1326
- const lastDay = this.daysInGregorianMonth(year, month);
1327
- let byMonthDayHits = [];
1328
- if (byMonthDay && byMonthDay.length > 0) {
1329
- byMonthDayHits = byMonthDay.map((day) => day > 0 ? day : lastDay + day + 1).filter((day) => day >= 1 && day <= lastDay);
1330
- byMonthDayHits = [...new Set(byMonthDayHits)].sort((a, b) => a - b);
1331
- }
1332
- if (!byDay && byMonthDay && byMonthDay.length > 0) {
1333
- return byMonthDayHits;
1334
- }
1335
- if (!byDay) {
1336
- const day = this.originalDtstart.day;
1337
- return day >= 1 && day <= lastDay ? [day] : [];
1338
- }
1339
- const tokens = this.parsedByDayTokens;
1340
- if (!(tokens == null ? void 0 : tokens.length)) return [];
1341
- const firstDayOfWeek = this.gregorianIsoDayOfWeek(year, month, 1);
1342
- const lastDayOfWeek = addIsoDays(firstDayOfWeek, lastDay - 1);
1343
- const byDayHits = /* @__PURE__ */ new Set();
1344
- for (const { ord, isoDay } of tokens) {
1345
- if (ord === 0) {
1346
- let day = 1 + (isoDay - firstDayOfWeek + 7) % 7;
1347
- while (day <= lastDay) {
1348
- byDayHits.add(day);
1349
- day += 7;
1350
- }
1351
- } else {
1352
- let day;
1353
- if (ord > 0) {
1354
- day = 1 + (isoDay - firstDayOfWeek + 7) % 7 + 7 * (ord - 1);
1355
- } else {
1356
- const lastMatch = lastDay - (lastDayOfWeek - isoDay + 7) % 7;
1357
- day = lastMatch + 7 * (ord + 1);
1358
- }
1359
- if (day >= 1 && day <= lastDay) {
1360
- byDayHits.add(day);
1361
- }
1362
- }
1363
- }
1364
- let finalDays = [...byDayHits].sort((a, b) => a - b);
1365
- if (byMonthDay && byMonthDay.length > 0) {
1366
- if (byMonthDayHits.length === 0) return [];
1367
- const byMonthDayHitSet = new Set(byMonthDayHits);
1368
- finalDays = finalDays.filter((day) => byMonthDayHitSet.has(day));
1369
- }
1370
- return finalDays;
1371
- }
1372
- generateMonthlyOccurrenceEpochsUtc(year, month) {
1373
- var _a;
1374
- const days = this.generateMonthlyOccurrenceDaysUtc(year, month);
1375
- if (days.length === 0) return [];
1376
- const monthStartMs = Date.UTC(year, month - 1, 1, 0, 0, 0, 0);
1377
- const timeSlotOffsets = (_a = this.timeSlotOffsetsMs) != null ? _a : [0];
1378
- if (this.opts.bySetPos && this.opts.bySetPos.length > 0) {
1379
- if (timeSlotOffsets.length === 1) {
1380
- const selectedDays = this.applyBySetPosToSortedList(days).sort((a, b) => a - b);
1381
- const offset = timeSlotOffsets[0];
1382
- return selectedDays.map((day) => monthStartMs + (day - 1) * MS_PER_DAY + offset);
1383
- }
1384
- const timestamps2 = [];
1385
- for (const day of days) {
1386
- const dayBase = monthStartMs + (day - 1) * MS_PER_DAY;
1387
- for (const offset of timeSlotOffsets) {
1388
- timestamps2.push(dayBase + offset);
1389
- }
1390
- }
1391
- return this.applyBySetPosToSortedList(timestamps2).sort((a, b) => a - b);
1392
- }
1393
- const timestamps = [];
1394
- for (const day of days) {
1395
- const dayBase = monthStartMs + (day - 1) * MS_PER_DAY;
1396
- for (const offset of timeSlotOffsets) {
1397
- timestamps.push(dayBase + offset);
1398
- }
1399
- }
1400
- return timestamps;
1401
- }
1402
- _allUtcMonthlyByDayOrMonthDay() {
1403
- var _a;
1404
- const dates = [];
1405
- const startMilliseconds = this.originalDtstart.epochMilliseconds;
1406
- const untilMilliseconds = (_a = this.opts.until) == null ? void 0 : _a.epochMilliseconds;
1407
- let iterationCount = 0;
1408
- if (!this.addDtstartIfNeeded(dates)) {
1409
- return dates;
1410
- }
1411
- let monthIndex = this.originalDtstart.year * 12 + (this.originalDtstart.month - 1);
1412
- while (true) {
1413
- if (++iterationCount > this.maxIterations) {
1414
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1415
- }
1416
- const { year, month } = this.monthIndexToYearMonth(monthIndex);
1417
- const occurrenceEpochs = this.generateMonthlyOccurrenceEpochsUtc(year, month);
1418
- for (const epochMilliseconds of occurrenceEpochs) {
1419
- if (epochMilliseconds < startMilliseconds) {
1420
- continue;
1421
- }
1422
- if (untilMilliseconds !== void 0 && epochMilliseconds > untilMilliseconds) {
1423
- return dates;
1424
- }
1425
- dates.push(this.utcZdtFromEpochMilliseconds(epochMilliseconds));
1426
- if (this.shouldBreakForCountLimit(dates.length)) {
1427
- return dates;
1428
- }
1429
- }
1430
- monthIndex += this.opts.interval;
1431
- }
1432
- }
1433
- processOccurrences(occs, dates, start, iterator, extraFilters) {
1434
- let shouldBreak = false;
1435
- for (const occ of occs) {
1436
- if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
1437
- if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
1438
- shouldBreak = true;
1439
- break;
1440
- }
1441
- if (extraFilters && !extraFilters(occ)) {
1442
- continue;
1443
- }
1444
- if (iterator && this.isExcluded(occ)) {
1445
- continue;
1446
- }
1447
- if (iterator && !iterator(occ, dates.length)) {
1448
- shouldBreak = true;
1449
- break;
1450
- }
1451
- dates.push(occ);
1452
- if (this.shouldBreakForCountLimit(dates.length)) {
1453
- shouldBreak = true;
1454
- break;
1455
- }
1456
- }
1457
- return { shouldBreak };
1458
- }
1459
- /**
1460
- * Returns all occurrences of the rule.
1461
- * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
1462
- * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
1463
- */
1464
- _allMonthlyByDayOrMonthDay(iterator) {
1465
- const dates = [];
1466
- let iterationCount = 0;
1467
- const start = this.originalDtstart;
1468
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1469
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1470
- }
1471
- let monthCursor = start.with({ day: 1 });
1472
- while (true) {
1473
- if (++iterationCount > this.maxIterations) {
1474
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1475
- }
1476
- let occs = this.generateMonthlyOccurrencesOptimizedBySetPos(monthCursor);
1477
- if (!occs) {
1478
- occs = this.generateMonthlyOccurrences(monthCursor);
1479
- occs = this.applyBySetPos(occs);
1480
- }
1481
- const { shouldBreak } = this.processOccurrences(occs, dates, start, iterator);
1482
- if (shouldBreak) {
1483
- break;
1484
- }
1485
- monthCursor = monthCursor.add({ months: this.opts.interval });
1486
- }
1487
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1488
- }
1489
- _allWeekly(iterator) {
1490
- var _a, _b, _c;
1491
- const dates = [];
1492
- let iterationCount = 0;
1493
- const start = this.originalDtstart;
1494
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1495
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1496
- }
1497
- const dayMap = weekdayToIsoDay;
1498
- const dows = this.opts.byDay ? [...(_a = this.allByDayIsoDays) != null ? _a : []] : this.opts.byMonthDay && this.opts.byMonthDay.length > 0 ? [...Object.values(dayMap)] : [start.dayOfWeek];
1499
- const firstWeekDates = dows.map((dw) => {
1500
- const delta = (dw - start.dayOfWeek + 7) % 7;
1501
- return start.add({ days: delta });
1502
- });
1503
- const firstOccurrence = firstWeekDates.reduce((a, b) => Temporal.ZonedDateTime.compare(a, b) <= 0 ? a : b);
1504
- const wkstToken = (_b = extractWeekdayToken(this.opts.wkst || "MO")) != null ? _b : "MO";
1505
- const wkstDay = (_c = dayMap[wkstToken]) != null ? _c : 1;
1506
- const firstOccWeekOffset = (firstOccurrence.dayOfWeek - wkstDay + 7) % 7;
1507
- let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
1508
- while (true) {
1509
- if (++iterationCount > this.maxIterations) {
1510
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1511
- }
1512
- let occs = dows.flatMap((dw) => {
1513
- const delta = (dw - wkstDay + 7) % 7;
1514
- const sameDate = weekCursor.add({ days: delta });
1515
- return this.expandByTime(sameDate);
1516
- }).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1517
- occs = this.applyBySetPos(occs);
1518
- const { shouldBreak } = this.processOccurrences(
1519
- occs,
1520
- dates,
1521
- start,
1522
- iterator,
1523
- (occ) => this.matchesByMonth(occ) && this.matchesByMonthDay(occ)
1524
- );
1525
- if (shouldBreak) {
1526
- break;
1527
- }
1528
- weekCursor = weekCursor.add({ weeks: this.opts.interval });
1529
- }
1530
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1531
- }
1532
- _allMonthlyByMonth(iterator) {
1533
- const dates = [];
1534
- let iterationCount = 0;
1535
- const start = this.originalDtstart;
1536
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1537
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1538
- }
1539
- const months = this.opts.byMonth.filter((v) => typeof v === "number").sort((a, b) => a - b);
1540
- let monthOffset = 0;
1541
- let startMonthIndex = months.findIndex((m) => m >= start.month);
1542
- if (startMonthIndex === -1) {
1543
- startMonthIndex = 0;
1544
- monthOffset = 1;
1545
- }
1546
- while (true) {
1547
- if (++iterationCount > this.maxIterations) {
1548
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1549
- }
1550
- const monthIndex = startMonthIndex + monthOffset;
1551
- const targetMonth = months[monthIndex % months.length];
1552
- const yearsToAdd = Math.floor(monthIndex / months.length);
1553
- const candidate = start.with({
1554
- year: start.year + yearsToAdd,
1555
- month: targetMonth
1556
- });
1557
- if (this.opts.until && Temporal.ZonedDateTime.compare(candidate, this.opts.until) > 0) {
1558
- break;
1559
- }
1560
- if (Temporal.ZonedDateTime.compare(candidate, start) >= 0) {
1561
- if (iterator && this.isExcluded(candidate)) {
1562
- continue;
1563
- }
1564
- if (iterator && !iterator(candidate, dates.length)) {
1565
- break;
1566
- }
1567
- dates.push(candidate);
1568
- if (this.shouldBreakForCountLimit(dates.length)) {
1569
- break;
1570
- }
1571
- }
1572
- monthOffset++;
1573
- }
1574
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1575
- }
1576
- _allYearlyByMonth(iterator) {
1577
- const dates = [];
1578
- let iterationCount = 0;
1579
- const start = this.originalDtstart;
1580
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1581
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1582
- }
1583
- const months = this.opts.byMonth.filter((v) => typeof v === "number").sort((a, b) => a - b);
1584
- let yearOffset = 0;
1585
- while (true) {
1586
- if (++iterationCount > this.maxIterations) {
1587
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1588
- }
1589
- const year = start.year + yearOffset * this.opts.interval;
1590
- for (const month of months) {
1591
- let occ = start.with({ year, month });
1592
- occ = this.applyTimeOverride(occ);
1593
- if (Temporal.ZonedDateTime.compare(occ, start) < 0) {
1594
- continue;
1595
- }
1596
- if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
1597
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1598
- }
1599
- if (iterator && this.isExcluded(occ)) {
1600
- continue;
1601
- }
1602
- if (iterator && !iterator(occ, dates.length)) {
1603
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1604
- }
1605
- dates.push(occ);
1606
- if (this.shouldBreakForCountLimit(dates.length)) {
1607
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1608
- }
1609
- }
1610
- yearOffset++;
1611
- }
1612
- }
1613
- _allYearlyComplex(iterator) {
1614
- const dates = [];
1615
- let iterationCount = 0;
1616
- const start = this.originalDtstart;
1617
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1618
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1619
- }
1620
- let yearCursor = start.with({ month: 1, day: 1 });
1621
- while (true) {
1622
- if (++iterationCount > this.maxIterations) {
1623
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1624
- }
1625
- const occs = this.generateYearlyOccurrences(yearCursor);
1626
- const uniqueOccs = [];
1627
- if (occs.length > 0) {
1628
- uniqueOccs.push(occs[0]);
1629
- for (let i = 1; i < occs.length; i++) {
1630
- if (Temporal.ZonedDateTime.compare(occs[i], occs[i - 1]) !== 0) {
1631
- uniqueOccs.push(occs[i]);
1632
- }
1633
- }
1634
- }
1635
- const { shouldBreak } = this.processOccurrences(uniqueOccs, dates, start, iterator);
1636
- if (shouldBreak) {
1637
- break;
1638
- }
1639
- const interval = this.opts.freq === "WEEKLY" ? 1 : this.opts.interval;
1640
- yearCursor = yearCursor.add({ years: interval });
1641
- if (this.opts.freq === "WEEKLY" && this.opts.until && yearCursor.year > this.opts.until.year) {
1642
- break;
1643
- }
1644
- }
1645
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1646
- }
1647
- _allMinutelySecondlyComplex(iterator) {
1648
- const dates = [];
1649
- let iterationCount = 0;
1650
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1651
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1652
- }
1653
- let current = this.computeFirst();
1654
- while (true) {
1655
- if (++iterationCount > this.maxIterations) {
1656
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1657
- }
1658
- if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
1659
- break;
1660
- }
1661
- if (this.matchesAll(current)) {
1662
- if (iterator && this.isExcluded(current)) {
1663
- current = this.nextCandidateSameDate(current);
1664
- continue;
1665
- }
1666
- if (iterator && !iterator(current, dates.length)) {
1667
- break;
1668
- }
1669
- dates.push(current);
1670
- if (this.shouldBreakForCountLimit(dates.length)) {
1671
- break;
1672
- }
1673
- current = this.nextCandidateSameDate(current);
1674
- } else {
1675
- current = this.findNextValidDate(current);
1676
- }
1677
- }
1678
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1679
- }
1680
- _allMonthlyByWeekNo(iterator) {
1681
- const dates = [];
1682
- let iterationCount = 0;
1683
- const start = this.originalDtstart;
1684
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1685
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1686
- }
1687
- let current = start;
1688
- const weekNos = [...this.opts.byWeekNo].sort((a, b) => a - b);
1689
- const interval = this.opts.interval;
1690
- let monthsAdvanced = 0;
1691
- let lastYearProcessed = -1;
1692
- outer_loop: while (true) {
1693
- if (this.shouldBreakForCountLimit(dates.length)) {
1694
- break;
1695
- }
1696
- if (++iterationCount > this.maxIterations) {
1697
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1698
- }
1699
- const year = current.year;
1700
- if (year !== lastYearProcessed && current.month >= start.month) {
1701
- lastYearProcessed = year;
1702
- for (const weekNo of weekNos) {
1703
- const occs = this.generateOccurrencesForWeekInYear(year, weekNo);
1704
- for (const occ of occs) {
1705
- if (Temporal.ZonedDateTime.compare(occ, start) >= 0) {
1706
- if (iterator && this.isExcluded(occ)) {
1707
- continue;
1708
- }
1709
- if (iterator && !iterator(occ, dates.length)) {
1710
- break outer_loop;
1711
- }
1712
- dates.push(occ);
1713
- if (this.shouldBreakForCountLimit(dates.length)) {
1714
- break outer_loop;
1715
- }
1716
- }
1717
- }
1718
- }
1719
- }
1720
- monthsAdvanced += interval;
1721
- current = start.add({ months: monthsAdvanced });
1722
- if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
1723
- break;
1724
- }
1725
- }
1726
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1727
- }
1728
- _allMonthlyByYearDay(iterator) {
1729
- const dates = [];
1730
- let iterationCount = 0;
1731
- const start = this.originalDtstart;
1732
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1733
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1734
- }
1735
- let year = start.year;
1736
- const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
1737
- const interval = this.opts.interval;
1738
- const startMonthAbs = start.year * 12 + start.month;
1739
- outer_loop: while (true) {
1740
- if (this.shouldBreakForCountLimit(dates.length)) {
1741
- break;
1742
- }
1743
- if (++iterationCount > this.maxIterations) {
1744
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1745
- }
1746
- const yearStart = start.with({ year, month: 1, day: 1 });
1747
- const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
1748
- for (const yd of yearDays) {
1749
- const dayNum = yd > 0 ? yd : lastDayOfYear + yd + 1;
1750
- if (dayNum <= 0 || dayNum > lastDayOfYear) continue;
1751
- const baseOcc = yearStart.add({ days: dayNum - 1 });
1752
- for (const occ of this.expandByTime(baseOcc)) {
1753
- if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
1754
- if (dates.some((d) => Temporal.ZonedDateTime.compare(d, occ) === 0)) continue;
1755
- const occMonthAbs = occ.year * 12 + occ.month;
1756
- if ((occMonthAbs - startMonthAbs) % interval !== 0) {
1757
- continue;
1758
- }
1759
- if (!this.matchesByMonth(occ)) {
1760
- continue;
1761
- }
1762
- if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
1763
- break outer_loop;
1764
- }
1765
- if (iterator && this.isExcluded(occ)) {
1766
- continue;
1767
- }
1768
- if (iterator && !iterator(occ, dates.length)) {
1769
- break outer_loop;
1770
- }
1771
- dates.push(occ);
1772
- if (this.shouldBreakForCountLimit(dates.length)) {
1773
- break outer_loop;
1774
- }
1775
- }
1776
- }
1777
- year++;
1778
- if (this.opts.until && year > this.opts.until.year + 2) {
1779
- break;
1780
- }
1781
- if (!this.opts.until && this.opts.count) {
1782
- const yearsToScan = Math.ceil(this.opts.count / (this.opts.byYearDay.length || 1)) * interval + 5;
1783
- if (year > start.year + yearsToScan) {
1784
- break;
1785
- }
1786
- }
1787
- }
1788
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1789
- }
1790
- _allDailyMinutelyHourlyWithBySetPos(iterator) {
1791
- const dates = [];
1792
- let iterationCount = 0;
1793
- const start = this.originalDtstart;
1794
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1795
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1796
- }
1797
- let cursor;
1798
- let duration;
1799
- switch (this.opts.freq) {
1800
- case "MINUTELY":
1801
- cursor = start.with({ second: 0, microsecond: 0, nanosecond: 0 });
1802
- duration = { minutes: this.opts.interval };
1803
- break;
1804
- case "HOURLY":
1805
- cursor = start.with({ minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
1806
- duration = { hours: this.opts.interval };
1807
- break;
1808
- case "DAILY":
1809
- cursor = start.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
1810
- duration = { days: this.opts.interval };
1811
- break;
1812
- default:
1813
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1814
- }
1815
- while (true) {
1816
- if (++iterationCount > this.maxIterations) {
1817
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1818
- }
1819
- let periodOccs = this.expandByTime(cursor);
1820
- periodOccs = periodOccs.filter((occ) => this.matchesAll(occ));
1821
- periodOccs = this.applyBySetPos(periodOccs);
1822
- const { shouldBreak } = this.processOccurrences(periodOccs, dates, start, iterator);
1823
- if (shouldBreak) {
1824
- break;
1825
- }
1826
- cursor = cursor.add(duration);
1827
- if (this.opts.until && Temporal.ZonedDateTime.compare(cursor, this.opts.until) > 0) {
1828
- break;
1829
- }
1830
- }
1831
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1832
- }
1833
- _allFallback(iterator) {
1834
- const dates = [];
1835
- let iterationCount = 0;
1836
- let current = this.computeFirst();
1837
- if (this.includeDtstart && Temporal.ZonedDateTime.compare(current, this.originalDtstart) > 0) {
1838
- if (iterator && this.isExcluded(this.originalDtstart)) {
1839
- } else {
1840
- if (iterator && !iterator(this.originalDtstart, dates.length)) {
1841
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1842
- }
1843
- dates.push(this.originalDtstart);
1844
- if (this.shouldBreakForCountLimit(dates.length)) {
1845
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1846
- }
1847
- }
1848
- }
1849
- while (true) {
1850
- if (++iterationCount > this.maxIterations) {
1851
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1852
- }
1853
- if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
1854
- break;
1855
- }
1856
- if (this.matchesAll(current)) {
1857
- if (iterator && this.isExcluded(current)) {
1858
- } else {
1859
- if (iterator && !iterator(current, dates.length)) {
1860
- break;
1861
- }
1862
- dates.push(current);
1863
- if (this.shouldBreakForCountLimit(dates.length)) {
1864
- break;
1865
- }
1866
- }
1867
- }
1868
- current = this.nextCandidateSameDate(current);
1869
- }
1870
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1871
- }
1872
- /**
1873
- * Returns all occurrences of the rule.
1874
- * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
1875
- * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
1876
- */
1877
- all(iterator) {
1878
- if (this.opts.rscale && ["CHINESE", "HEBREW", "INDIAN"].includes(this.opts.rscale)) {
1879
- if (["YEARLY", "MONTHLY", "WEEKLY"].includes(this.opts.freq) || !!this.opts.byYearDay || !!this.opts.byWeekNo || this.opts.byMonthDay && this.opts.byMonthDay.length > 0) {
1880
- return this._allRscaleNonGregorian(iterator);
1881
- }
1882
- }
1883
- if (this.opts.byWeekNo && this.opts.byYearDay) {
1884
- const yearStart = this.originalDtstart.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 });
1885
- const yearDays = this.opts.byYearDay.map((yd) => {
1886
- const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
1887
- return yd > 0 ? yd : lastDayOfYear + yd + 1;
1888
- });
1889
- let possibleDate = false;
1890
- for (const yd of yearDays) {
1891
- const date = yearStart.add({ days: yd - 1 });
1892
- if (this.matchesByWeekNo(date)) {
1893
- possibleDate = true;
1894
- break;
1895
- }
1896
- }
1897
- if (!possibleDate) {
1898
- return [];
1899
- }
1900
- }
1901
- if (!this.opts.count && !this.opts.until && !iterator) {
1902
- throw new Error("all() requires iterator when no COUNT/UNTIL");
1903
- }
1904
- const utcFastPathDates = this.allUtcFastPath(iterator);
1905
- if (utcFastPathDates) {
1906
- return utcFastPathDates;
1907
- }
1908
- if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay) && !this.opts.byWeekNo) {
1909
- return this._allMonthlyByDayOrMonthDay(iterator);
1910
- }
1911
- if (this.opts.freq === "WEEKLY" && !(this.opts.byYearDay && this.opts.byYearDay.length > 0) && !(this.opts.byWeekNo && this.opts.byWeekNo.length > 0)) {
1912
- return this._allWeekly(iterator);
1913
- }
1914
- if (this.opts.freq === "MONTHLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay) {
1915
- return this._allMonthlyByMonth(iterator);
1916
- }
1917
- if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay && !this.opts.byWeekNo) {
1918
- return this._allYearlyByMonth(iterator);
1919
- }
1920
- 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) {
1921
- return this._allYearlyComplex(iterator);
1922
- }
1923
- if ((this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") && (this.opts.byMonth || this.opts.byWeekNo || this.opts.byYearDay || this.opts.byMonthDay || this.opts.byDay)) {
1924
- return this._allMinutelySecondlyComplex(iterator);
1925
- }
1926
- if (this.opts.freq === "MONTHLY" && this.opts.byWeekNo && this.opts.byWeekNo.length > 0) {
1927
- return this._allMonthlyByWeekNo(iterator);
1928
- }
1929
- if (this.opts.freq === "MONTHLY" && this.opts.byYearDay && this.opts.byYearDay.length > 0 && !this.opts.byDay && !this.opts.byMonthDay) {
1930
- return this._allMonthlyByYearDay(iterator);
1931
- }
1932
- if (this.opts.rscale && this.opts.freq === "MONTHLY" && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byWeekNo && !this.opts.byYearDay) {
1933
- return this._allMonthlyRscaleSimple(iterator);
1934
- }
1935
- if ((this.opts.freq === "MINUTELY" || this.opts.freq === "HOURLY" || this.opts.freq === "DAILY") && this.opts.bySetPos) {
1936
- return this._allDailyMinutelyHourlyWithBySetPos(iterator);
1937
- }
1938
- return this._allFallback(iterator);
1939
- }
1940
- /**
1941
- * RFC 7529: RSCALE present, simple monthly iteration with SKIP behavior.
1942
- * Handles month-to-month stepping from DTSTART's year/month aiming for DTSTART's day-of-month.
1943
- * Applies SKIP=OMIT (skip invalid months), BACKWARD (clamp to last day), FORWARD (first day of next month).
1944
- */
1945
- _allMonthlyRscaleSimple(iterator) {
1946
- var _a;
1947
- const dates = [];
1948
- let iterationCount = 0;
1949
- const start = this.originalDtstart;
1950
- const interval = (_a = this.opts.interval) != null ? _a : 1;
1951
- const targetDom = start.day;
1952
- if (!this.addDtstartIfNeeded(dates, iterator)) {
1953
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1954
- }
1955
- let cursor = start.with({ day: 1 });
1956
- while (true) {
1957
- if (++iterationCount > this.maxIterations) {
1958
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1959
- }
1960
- const lastDay = cursor.add({ months: 1 }).subtract({ days: 1 }).day;
1961
- let occ = null;
1962
- if (targetDom <= lastDay) {
1963
- occ = cursor.with({ day: targetDom });
1964
- } else {
1965
- const skip = this.opts.skip || "OMIT";
1966
- if (skip === "BACKWARD") {
1967
- occ = cursor.with({ day: lastDay });
1968
- } else if (skip === "FORWARD") {
1969
- occ = cursor.add({ months: 1 }).with({ day: 1 });
1970
- } else {
1971
- occ = null;
1972
- }
1973
- }
1974
- if (occ) {
1975
- occ = occ.with({ hour: start.hour, minute: start.minute, second: start.second });
1976
- if (!(iterator && this.isExcluded(occ))) {
1977
- if (Temporal.ZonedDateTime.compare(occ, start) >= 0) {
1978
- if (!iterator || iterator(occ, dates.length)) {
1979
- dates.push(occ);
1980
- if (this.shouldBreakForCountLimit(dates.length)) break;
1981
- } else {
1982
- break;
1983
- }
1984
- }
1985
- }
1986
- }
1987
- cursor = cursor.add({ months: interval });
1988
- if (this.opts.until && Temporal.ZonedDateTime.compare(cursor, this.opts.until) > 0) {
1989
- break;
1990
- }
1991
- }
1992
- return this.applyCountLimitAndMergeRDates(dates, iterator);
1993
- }
1994
- /**
1995
- * Converts rDate entries to ZonedDateTime and merges with existing dates.
1996
- * @param dates - Array of dates to merge with
1997
- * @returns Merged and deduplicated array of dates
1998
- */
1999
- mergeAndDeduplicateRDates(dates) {
2000
- if (this.opts.rDate) {
2001
- dates.push(...this.opts.rDate);
2002
- }
2003
- dates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2004
- const dedup = [];
2005
- for (const d of dates) {
2006
- if (dedup.length === 0 || Temporal.ZonedDateTime.compare(d, dedup[dedup.length - 1]) !== 0) {
2007
- dedup.push(d);
2008
- }
2009
- }
2010
- return dedup;
2011
- }
2012
- /**
2013
- * Checks if a date is in the exDate list.
2014
- * @param date - Date to check
2015
- * @returns True if the date is excluded
2016
- */
2017
- isExcluded(date) {
2018
- if (!this.opts.exDate || this.opts.exDate.length === 0) return false;
2019
- return this.opts.exDate.some((exDate) => Temporal.ZonedDateTime.compare(date, exDate) === 0);
2020
- }
2021
- /**
2022
- * Excludes exDate entries from the given array of dates.
2023
- * @param dates - Array of dates to filter
2024
- * @returns Filtered array with exDate entries removed
2025
- */
2026
- excludeExDates(dates) {
2027
- if (!this.opts.exDate || this.opts.exDate.length === 0) return dates;
2028
- return dates.filter((date) => {
2029
- return !this.isExcluded(date);
2030
- });
2031
- }
2032
- /**
2033
- * Applies count limit and merges rDates with the rule-generated dates.
2034
- * @param dates - Array of dates generated by the rule
2035
- * @param iterator - Optional iterator function
2036
- * @returns Final array of dates after merging and applying count limit
2037
- */
2038
- applyCountLimitAndMergeRDates(dates, iterator) {
2039
- const merged = this.mergeAndDeduplicateRDates(dates);
2040
- const excluded = this.excludeExDates(merged);
2041
- const hasCountLimit = this.opts.count !== void 0;
2042
- if (!hasCountLimit && !iterator) {
2043
- return excluded;
2044
- }
2045
- let emitted = 0;
2046
- const max = hasCountLimit ? this.opts.count : Infinity;
2047
- const finalDates = [];
2048
- for (const d of excluded) {
2049
- if (emitted >= max) break;
2050
- if (iterator && !iterator(d, emitted)) break;
2051
- finalDates.push(d);
2052
- emitted++;
2053
- }
2054
- return finalDates;
2055
- }
2056
- /**
2057
- * Checks if the count limit should break the loop based on rDate presence.
2058
- * @param matchCount - Current number of matches
2059
- * @returns true if the loop should break
2060
- */
2061
- shouldBreakForCountLimit(matchCount) {
2062
- if (this.opts.count === void 0) return false;
2063
- if (!this.opts.rDate) {
2064
- return matchCount >= this.opts.count;
2065
- }
2066
- const rDateCount = this.opts.rDate.length;
2067
- const targetRuleCount = Math.max(this.opts.count - rDateCount, 0);
2068
- const safetyMargin = Math.min(targetRuleCount, 10);
2069
- return matchCount >= targetRuleCount + safetyMargin;
2070
- }
2071
- hasTimeOfDayBetween(startTime, endTime) {
2072
- var _a, _b, _c;
2073
- if (Temporal.PlainTime.compare(startTime, endTime) >= 0) return false;
2074
- const base = this.originalDtstart;
2075
- const hours = (_a = this.opts.byHour) != null ? _a : [base.hour];
2076
- const minutes = (_b = this.opts.byMinute) != null ? _b : [base.minute];
2077
- const seconds = (_c = this.opts.bySecond) != null ? _c : [base.second];
2078
- for (const hour of hours) {
2079
- for (const minute of minutes) {
2080
- for (const second of seconds) {
2081
- const candidate = Temporal.PlainTime.from({
2082
- hour,
2083
- minute,
2084
- second,
2085
- millisecond: base.millisecond,
2086
- microsecond: base.microsecond,
2087
- nanosecond: base.nanosecond
2088
- });
2089
- if (Temporal.PlainTime.compare(candidate, startTime) >= 0 && Temporal.PlainTime.compare(candidate, endTime) < 0) {
2090
- return true;
2091
- }
2092
- }
2093
- }
2094
- }
2095
- return false;
2096
- }
2097
- /**
2098
- * Returns all occurrences of the rule within a specified time window.
2099
- * @param after - The start date or Temporal.ZonedDateTime object.
2100
- * @param before - The end date or Temporal.ZonedDateTime object.
2101
- * @param inc - Optional boolean flag to include the end date in the results.
2102
- * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule within the specified time window.
2103
- */
2104
- between(after, before, inc = false) {
2105
- var _a;
2106
- const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
2107
- const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
2108
- const startZdt = Temporal.Instant.from(startInst).toZonedDateTimeISO(this.tzid);
2109
- const beforeZdt = Temporal.Instant.from(endInst).toZonedDateTimeISO(this.tzid);
2110
- const tempOpts = __spreadValues({}, this.opts);
2111
- if (!tempOpts.until || Temporal.ZonedDateTime.compare(beforeZdt, tempOpts.until) < 0) {
2112
- tempOpts.until = beforeZdt;
2113
- }
2114
- if (tempOpts.count === void 0) {
2115
- const interval = (_a = tempOpts.interval) != null ? _a : 1;
2116
- const aligned = startZdt.withPlainTime(this.originalDtstart.toPlainTime());
2117
- let unit;
2118
- switch (tempOpts.freq) {
2119
- case "YEARLY":
2120
- unit = "years";
2121
- break;
2122
- case "MONTHLY":
2123
- unit = "months";
2124
- break;
2125
- case "WEEKLY":
2126
- unit = "weeks";
2127
- break;
2128
- case "DAILY":
2129
- unit = "days";
2130
- break;
2131
- case "HOURLY":
2132
- unit = "hours";
2133
- break;
2134
- case "MINUTELY":
2135
- unit = "minutes";
2136
- break;
2137
- default:
2138
- unit = "seconds";
2139
- }
2140
- const dtstartNormalized = _RRuleTemporal.normalizeToPolyfill(this.opts.dtstart);
2141
- const startZdtNormalized = _RRuleTemporal.normalizeToPolyfill(startZdt).withTimeZone(dtstartNormalized.timeZoneId);
2142
- const alignedNormalized = _RRuleTemporal.normalizeToPolyfill(
2143
- aligned.withPlainTime(this.originalDtstart.toPlainTime())
2144
- ).withTimeZone(dtstartNormalized.timeZoneId);
2145
- const diffAnchor = ["hours", "minutes", "seconds"].includes(unit) ? startZdtNormalized : alignedNormalized;
2146
- const diffDur = dtstartNormalized.until(diffAnchor, { largestUnit: unit });
2147
- const unitsBetween = diffDur[unit];
2148
- let steps = Math.floor(unitsBetween / interval);
2149
- const durationForJump = (jump) => {
2150
- switch (unit) {
2151
- case "years":
2152
- return { years: jump };
2153
- case "months":
2154
- return { months: jump };
2155
- case "weeks":
2156
- return { weeks: jump };
2157
- case "days":
2158
- return { days: jump };
2159
- case "hours":
2160
- return { hours: jump };
2161
- case "minutes":
2162
- return { minutes: jump };
2163
- default:
2164
- return { seconds: jump };
2165
- }
2166
- };
2167
- let candidate = _RRuleTemporal.normalizeToPolyfill(this.opts.dtstart.add(durationForJump(steps * interval)));
2168
- if (steps > 0 && ["years", "months", "weeks", "days"].includes(unit)) {
2169
- const sameDate = candidate.toPlainDate().equals(startZdtNormalized.toPlainDate());
2170
- if (sameDate && Temporal.ZonedDateTime.compare(candidate, startZdtNormalized) > 0) {
2171
- if (this.hasTimeOfDayBetween(startZdtNormalized.toPlainTime(), candidate.toPlainTime())) {
2172
- steps -= 1;
2173
- candidate = _RRuleTemporal.normalizeToPolyfill(this.opts.dtstart.add(durationForJump(steps * interval)));
2174
- }
2175
- }
2176
- }
2177
- const dtstartForCompare = _RRuleTemporal.normalizeToPolyfill(this.opts.dtstart);
2178
- if (Temporal.ZonedDateTime.compare(candidate, dtstartForCompare) < 0) {
2179
- candidate = dtstartForCompare;
2180
- }
2181
- tempOpts.dtstart = candidate;
2182
- }
2183
- const tempRule = new _RRuleTemporal(tempOpts);
2184
- const allDates = tempRule.all();
2185
- return allDates.filter((date) => {
2186
- const inst = date.toInstant();
2187
- const afterStart = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
2188
- const beforeEnd = inc ? Temporal.Instant.compare(inst, endInst) <= 0 : Temporal.Instant.compare(inst, endInst) < 0;
2189
- return afterStart && beforeEnd;
2190
- });
2191
- }
2192
- /**
2193
- * Convenience helper: true if the exact instant is an occurrence of the rule.
2194
- * This checks full date-time equality (including time and time zone).
2195
- */
2196
- matches(date) {
2197
- return this.between(date, date, true).length > 0;
2198
- }
2199
- /**
2200
- * Convenience helper: true if any occurrence falls on the given calendar day
2201
- * in the rule's time zone. This ignores time-of-day granularity.
2202
- */
2203
- occursOn(date) {
2204
- const startOfDay = date.toZonedDateTime({
2205
- timeZone: this.tzid,
2206
- plainTime: Temporal.PlainTime.from("00:00")
2207
- });
2208
- const endOfDay = startOfDay.add({ days: 1 }).subtract({ nanoseconds: 1 });
2209
- return this.between(startOfDay, endOfDay, true).length > 0;
2210
- }
2211
- /**
2212
- * Returns the next occurrence of the rule after a specified date.
2213
- * @param after - The start date or Temporal.ZonedDateTime object.
2214
- * @param inc - Optional boolean flag to include occurrences on the start date.
2215
- * @returns The next occurrence of the rule after the specified date or null if no occurrences are found.
2216
- */
2217
- next(after = /* @__PURE__ */ new Date(), inc = false) {
2218
- const afterInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
2219
- let result = null;
2220
- this.all((occ) => {
2221
- const inst = occ.toInstant();
2222
- const ok = inc ? Temporal.Instant.compare(inst, afterInst) >= 0 : Temporal.Instant.compare(inst, afterInst) > 0;
2223
- if (ok) {
2224
- if (!result || Temporal.ZonedDateTime.compare(occ, result) < 0) {
2225
- result = occ;
2226
- }
2227
- return false;
2228
- }
2229
- return true;
2230
- });
2231
- return result;
2232
- }
2233
- /**
2234
- * Returns the previous occurrence of the rule before a specified date.
2235
- * @param before - The end date or Temporal.ZonedDateTime object.
2236
- * @param inc - Optional boolean flag to include occurrences on the end date.
2237
- * @returns The previous occurrence of the rule before the specified date or null if no occurrences are found.
2238
- */
2239
- previous(before = /* @__PURE__ */ new Date(), inc = false) {
2240
- const beforeInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
2241
- let prev = null;
2242
- this.all((occ) => {
2243
- const inst = occ.toInstant();
2244
- const beyond = inc ? Temporal.Instant.compare(inst, beforeInst) > 0 : Temporal.Instant.compare(inst, beforeInst) >= 0;
2245
- if (beyond) return false;
2246
- prev = occ;
2247
- return true;
2248
- });
2249
- return prev;
2250
- }
2251
- toString() {
2252
- const iso = this.originalDtstart.toString({ smallestUnit: "second" }).replace(/[-:]/g, "");
2253
- const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
2254
- const rule = [];
2255
- const {
2256
- freq,
2257
- interval,
2258
- count,
2259
- until,
2260
- byHour,
2261
- byMinute,
2262
- bySecond,
2263
- byDay,
2264
- byMonth,
2265
- byMonthDay,
2266
- bySetPos,
2267
- byWeekNo,
2268
- byYearDay,
2269
- wkst,
2270
- rDate,
2271
- exDate
2272
- } = this.opts;
2273
- if (this.opts.rscale) rule.push(`RSCALE=${this.opts.rscale}`);
2274
- if (this.opts.rscale && this.opts.skip) rule.push(`SKIP=${this.opts.skip}`);
2275
- rule.push(`FREQ=${freq}`);
2276
- if (interval !== 1) rule.push(`INTERVAL=${interval}`);
2277
- if (count !== void 0) rule.push(`COUNT=${count}`);
2278
- if (until) {
2279
- rule.push(`UNTIL=${this.formatIcsDateTime(until)}`);
2280
- }
2281
- if (byHour) rule.push(`BYHOUR=${byHour.join(",")}`);
2282
- if (byMinute) rule.push(`BYMINUTE=${byMinute.join(",")}`);
2283
- if (bySecond) rule.push(`BYSECOND=${bySecond.join(",")}`);
2284
- if (byDay) rule.push(`BYDAY=${byDay.join(",")}`);
2285
- if (byMonth) rule.push(`BYMONTH=${byMonth.join(",")}`);
2286
- if (byMonthDay) rule.push(`BYMONTHDAY=${byMonthDay.join(",")}`);
2287
- if (bySetPos) rule.push(`BYSETPOS=${bySetPos.join(",")}`);
2288
- if (byWeekNo) rule.push(`BYWEEKNO=${byWeekNo.join(",")}`);
2289
- if (byYearDay) rule.push(`BYYEARDAY=${byYearDay.join(",")}`);
2290
- if (wkst) rule.push(`WKST=${wkst}`);
2291
- const lines = [dtLine, `RRULE:${rule.join(";")}`];
2292
- if (rDate) {
2293
- lines.push(`RDATE:${this.joinDates(rDate)}`);
2294
- }
2295
- if (exDate) {
2296
- lines.push(`EXDATE:${this.joinDates(exDate)}`);
2297
- }
2298
- return lines.join("\n");
2299
- }
2300
- formatIcsDateTime(date) {
2301
- return date.toInstant().toString().replace(/[-:]/g, "").slice(0, 15) + "Z";
2302
- }
2303
- joinDates(dates) {
2304
- return dates.map((d) => this.formatIcsDateTime(d));
2305
- }
2306
- /**
2307
- * Given any date in a month, return all the ZonedDateTimes in that month
2308
- * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
2309
- */
2310
- generateMonthlyOccurrences(sample) {
2311
- const monthStart = sample.day === 1 ? sample : sample.with({ day: 1 });
2312
- if (!this.opts.byDay && !this.opts.byMonthDay) {
2313
- return this.expandByTime(sample);
2314
- }
2315
- const finalDays = this.generateMonthlyOccurrenceDays(monthStart);
2316
- if (finalDays.length === 0) return [];
2317
- const hits = finalDays.map((d) => monthStart.with({ day: d }));
2318
- return hits.flatMap((z) => this.expandByTime(z));
2319
- }
2320
- /**
2321
- * Given any date in a year, return all ZonedDateTimes in that year matching
2322
- * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
2323
- * if BYMONTH is not specified.
2324
- */
2325
- generateYearlyOccurrences(sample) {
2326
- const months = this.opts.byMonth ? this.opts.byMonth.filter((v) => typeof v === "number").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];
2327
- let occs = [];
2328
- const hasOrdinalByDay = this.opts.byDay && this.opts.byDay.some((t) => /^[+-]?\d/.test(t));
2329
- if (hasOrdinalByDay && !this.opts.byMonth) {
2330
- const dayMap = weekdayToIsoDay;
2331
- for (const tok of this.opts.byDay) {
2332
- const parsed = parseByDayToken(tok);
2333
- if (!parsed || parsed.ord === 0) continue;
2334
- const ord = parsed.ord;
2335
- const wd = dayMap[parsed.weekday];
2336
- let dt;
2337
- if (ord > 0) {
2338
- const jan1 = sample.with({ month: 1, day: 1 });
2339
- const delta = (wd - jan1.dayOfWeek + 7) % 7;
2340
- dt = jan1.add({ days: delta + 7 * (ord - 1) });
2341
- } else {
2342
- const dec31 = sample.with({ month: 12, day: 31 });
2343
- const delta = (dec31.dayOfWeek - wd + 7) % 7;
2344
- dt = dec31.subtract({ days: delta + 7 * (-ord - 1) });
2345
- }
2346
- occs.push(...this.expandByTime(dt));
2347
- }
2348
- } else if (!this.opts.byYearDay && !this.opts.byWeekNo) {
2349
- occs = [];
2350
- for (const m of months) {
2351
- const monthSample = sample.with({ month: m, day: 1 });
2352
- const monthOccs = this.generateMonthlyOccurrences(monthSample);
2353
- if (monthOccs.length === 0 && this.opts.rscale && this.opts.byMonthDay && this.opts.byMonthDay.length > 0) {
2354
- const lastDay = monthSample.add({ months: 1 }).subtract({ days: 1 }).day;
2355
- const target = this.opts.byMonthDay[0];
2356
- const absTarget = target > 0 ? target : lastDay + target + 1;
2357
- if (absTarget > lastDay || absTarget <= 0) {
2358
- const skip = this.opts.skip || "OMIT";
2359
- if (skip === "BACKWARD") {
2360
- occs.push(...this.expandByTime(monthSample.with({ day: lastDay })));
2361
- } else if (skip === "FORWARD") {
2362
- const nextMonth = monthSample.add({ months: 1 }).with({ day: 1 });
2363
- occs.push(...this.expandByTime(nextMonth));
2364
- } else {
2365
- }
2366
- }
2367
- } else {
2368
- occs.push(...monthOccs);
2369
- }
2370
- }
2371
- }
2372
- if (this.opts.byYearDay) {
2373
- const last = sample.with({ month: 12, day: 31 }).dayOfYear;
2374
- for (const d of this.opts.byYearDay) {
2375
- const dayNum = d > 0 ? d : last + d + 1;
2376
- if (dayNum <= 0 || dayNum > last) continue;
2377
- 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 });
2378
- if (!this.opts.byMonth || this.opts.byMonth.includes(dt.month)) {
2379
- occs.push(...this.expandByTime(dt));
2380
- }
2381
- }
2382
- }
2383
- if (this.opts.byWeekNo) {
2384
- const { lastWeek, firstWeekStart, tokens } = this.isoWeekByDay(sample);
2385
- for (const weekNo of this.opts.byWeekNo) {
2386
- if (weekNo > 0 && weekNo > lastWeek || weekNo < 0 && -weekNo > lastWeek) {
2387
- continue;
2388
- }
2389
- const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
2390
- const weekStart = firstWeekStart.add({ weeks: weekIndex });
2391
- occs.push(...this.addByDay(tokens, weekStart));
2392
- }
2393
- }
2394
- occs = occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2395
- occs = this.applyBySetPos(occs);
2396
- return occs;
2397
- }
2398
- addByDay(tokens, weekStart) {
2399
- const dayMap = weekdayToIsoDay;
2400
- const wkst = dayMap[this.opts.wkst || "MO"];
2401
- const entries = [];
2402
- for (const tok of tokens) {
2403
- if (!tok) continue;
2404
- const targetDow = dayMap[tok];
2405
- const inst = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
2406
- if (!this.opts.byMonth || this.opts.byMonth.includes(inst.month)) {
2407
- entries.push(...this.expandByTime(inst));
2408
- }
2409
- }
2410
- return entries;
2411
- }
2412
- /**
2413
- * Helper to find the next valid value from a sorted array
2414
- */
2415
- findNextValidValue(currentValue, validValues, compare) {
2416
- return validValues.find((v) => compare(v, currentValue) > 0) || null;
2417
- }
2418
- /**
2419
- * Efficiently find the next valid date for MINUTELY and SECONDLY frequency by jumping over
2420
- * large gaps when BYXXX constraints don't match.
2421
- */
2422
- findNextValidDate(current) {
2423
- if (this.opts.byWeekNo && this.opts.byYearDay) {
2424
- const yearStart = current.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 });
2425
- const yearDays = this.opts.byYearDay.map((yd) => {
2426
- const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
2427
- return yd > 0 ? yd : lastDayOfYear + yd + 1;
2428
- });
2429
- for (const yd of yearDays) {
2430
- const date = yearStart.add({ days: yd - 1 });
2431
- if (this.matchesByWeekNo(date)) {
2432
- break;
2433
- }
2434
- }
2435
- }
2436
- if (this.opts.byMonth) {
2437
- const numericMonths = this.opts.byMonth.filter((v) => typeof v === "number");
2438
- if (numericMonths.length && !numericMonths.includes(current.month)) {
2439
- const months = [...numericMonths].sort((a, b) => a - b);
2440
- const nextMonth = this.findNextValidValue(current.month, months, (a, b) => a - b);
2441
- if (nextMonth) {
2442
- current = current.with({ month: nextMonth, day: 1, hour: 0, minute: 0, second: 0 });
2443
- } else {
2444
- current = current.add({ years: 1 }).with({ month: months[0], day: 1, hour: 0, minute: 0, second: 0 });
2445
- }
2446
- current = this.applyTimeOverride(current);
2447
- return current;
2448
- }
2449
- }
2450
- if (this.opts.byWeekNo && !this.matchesByWeekNo(current)) {
2451
- current = current.add({ weeks: 1 }).with({ hour: 0, minute: 0, second: 0 });
2452
- current = this.applyTimeOverride(current);
2453
- return current;
2454
- }
2455
- if (this.opts.byYearDay && !this.matchesByYearDay(current)) {
2456
- const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
2457
- const currentYearDay = current.dayOfYear;
2458
- const lastDayOfYear = current.with({ month: 12, day: 31 }).dayOfYear;
2459
- let nextYearDay = yearDays.find((d) => {
2460
- const dayNum = d > 0 ? d : lastDayOfYear + d + 1;
2461
- return dayNum > currentYearDay;
2462
- });
2463
- if (nextYearDay) {
2464
- const dayNum = nextYearDay > 0 ? nextYearDay : lastDayOfYear + nextYearDay + 1;
2465
- if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
2466
- current = current.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
2467
- } else {
2468
- current = current.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
2469
- }
2470
- } else {
2471
- const nextYear = current.add({ years: 1 });
2472
- const nextYearLastDay = nextYear.with({ month: 12, day: 31 }).dayOfYear;
2473
- const firstYearDay = yearDays[0];
2474
- if (firstYearDay !== void 0) {
2475
- const dayNum = firstYearDay > 0 ? firstYearDay : nextYearLastDay + firstYearDay + 1;
2476
- if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
2477
- current = nextYear.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
2478
- } else {
2479
- current = nextYear.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
2480
- }
2481
- }
2482
- }
2483
- current = this.applyTimeOverride(current);
2484
- return current;
2485
- }
2486
- if (this.opts.byMonthDay && !this.matchesByMonthDay(current)) {
2487
- const monthDays = [...this.opts.byMonthDay].sort((a, b) => a - b);
2488
- const lastDayOfMonth = current.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
2489
- const currentDay = current.day;
2490
- const validDays = monthDays.map((d) => d > 0 ? d : lastDayOfMonth + d + 1).filter((d) => d > 0 && d <= lastDayOfMonth).sort((a, b) => a - b);
2491
- const nextDay = this.findNextValidValue(currentDay, validDays, (a, b) => a - b);
2492
- if (nextDay) {
2493
- current = current.with({ day: nextDay, hour: 0, minute: 0, second: 0 });
2494
- } else {
2495
- const nextMonth = current.add({ months: 1 }).with({ day: 1 });
2496
- const nextMonthLastDay = nextMonth.add({ months: 1 }).subtract({ days: 1 }).day;
2497
- const firstMonthDay = monthDays[0];
2498
- if (firstMonthDay !== void 0) {
2499
- const dayNum = firstMonthDay > 0 ? firstMonthDay : nextMonthLastDay + firstMonthDay + 1;
2500
- current = nextMonth.with({
2501
- day: Math.max(1, Math.min(dayNum, nextMonthLastDay)),
2502
- hour: 0,
2503
- minute: 0,
2504
- second: 0
2505
- });
2506
- } else {
2507
- current = current.add({ months: 1 }).with({ day: 1, hour: 0, minute: 0, second: 0 });
2508
- }
2509
- }
2510
- current = this.applyTimeOverride(current);
2511
- return current;
2512
- }
2513
- if (this.opts.byDay && !this.matchesByDay(current)) {
2514
- const targetDays = this.allByDayIsoDays;
2515
- if (!(targetDays == null ? void 0 : targetDays.length)) {
2516
- return this.applyTimeOverride(current.add({ days: 1 }).with({ hour: 0, minute: 0, second: 0 }));
2517
- }
2518
- const nextDayOfWeek = this.findNextValidValue(current.dayOfWeek, targetDays, (a, b) => a - b);
2519
- if (nextDayOfWeek) {
2520
- const delta = (nextDayOfWeek - current.dayOfWeek + 7) % 7;
2521
- current = current.add({ days: delta }).with({ hour: 0, minute: 0, second: 0 });
2522
- } else {
2523
- const delta = (targetDays[0] - current.dayOfWeek + 7) % 7;
2524
- current = current.add({ days: delta + 7 }).with({ hour: 0, minute: 0, second: 0 });
2525
- }
2526
- current = this.applyTimeOverride(current);
2527
- return current;
2528
- }
2529
- switch (this.opts.freq) {
2530
- case "SECONDLY":
2531
- case "MINUTELY":
2532
- current = current.add({ days: 1 }).with({ hour: 0, minute: 0, second: 0 });
2533
- break;
2534
- case "HOURLY":
2535
- current = current.add({ days: 1 }).with({ hour: 0, minute: 0, second: 0 });
2536
- break;
2537
- case "DAILY":
2538
- case "WEEKLY":
2539
- current = current.add({ months: 1 }).with({ day: 1, hour: 0, minute: 0, second: 0 });
2540
- break;
2541
- case "MONTHLY":
2542
- case "YEARLY":
2543
- current = current.add({ years: 1 }).with({ month: 1, day: 1, hour: 0, minute: 0, second: 0 });
2544
- break;
2545
- }
2546
- return this.applyTimeOverride(current);
2547
- }
2548
- applyBySetPos(list) {
2549
- const { bySetPos } = this.opts;
2550
- if (!bySetPos || !bySetPos.length) return list;
2551
- const sorted = [...list].sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2552
- const out = this.applyBySetPosToSortedList(sorted);
2553
- return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2554
- }
2555
- isoWeekByDay(sample) {
2556
- var _a;
2557
- const dayMap = weekdayToIsoDay;
2558
- const wkst = dayMap[this.opts.wkst || "MO"];
2559
- const jan1 = sample.with({ month: 1, day: 1 });
2560
- const jan4 = sample.with({ month: 1, day: 4 });
2561
- const delta = (jan4.dayOfWeek - wkst + 7) % 7;
2562
- const firstWeekStart = jan4.subtract({ days: delta });
2563
- const isLeapYear = jan1.inLeapYear;
2564
- const lastWeek = jan1.dayOfWeek === 4 || isLeapYear && jan1.dayOfWeek === 3 ? 53 : 52;
2565
- const tokens = ((_a = this.opts.byDay) == null ? void 0 : _a.length) ? this.opts.byDay.map((tok) => extractWeekdayToken(tok)).filter((day) => day !== null) : [Object.entries(dayMap).find(([, d]) => d === this.originalDtstart.dayOfWeek)[0]];
2566
- return { lastWeek, firstWeekStart, tokens };
2567
- }
2568
- /**
2569
- * Generate occurrences for a specific week number in a given year
2570
- */
2571
- generateOccurrencesForWeekInYear(year, weekNo) {
2572
- const occs = [];
2573
- const sample = this.originalDtstart.with({ year, month: 1, day: 1 });
2574
- const { lastWeek, firstWeekStart, tokens } = this.isoWeekByDay(sample);
2575
- if (weekNo > 0 && weekNo > lastWeek || weekNo < 0 && -weekNo > lastWeek) {
2576
- return occs;
2577
- }
2578
- const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
2579
- const weekStart = firstWeekStart.add({ weeks: weekIndex });
2580
- occs.push(...this.addByDay(tokens, weekStart));
2581
- return occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2582
- }
2583
- // ===== RSCALE (non-Gregorian) support: Chinese and Hebrew =====
2584
- getRscaleCalendarId() {
2585
- var _a;
2586
- const map = {
2587
- GREGORIAN: "gregory",
2588
- CHINESE: "chinese",
2589
- HEBREW: "hebrew",
2590
- INDIAN: "indian"
2591
- };
2592
- const r = ((_a = this.opts.rscale) == null ? void 0 : _a.toUpperCase()) || "";
2593
- return map[r] || null;
2594
- }
2595
- assertRscaleCalendarSupported(calId) {
2596
- if (calId === "gregory" || calId === "iso8601") return;
2597
- const cached = _RRuleTemporal.rscaleCalendarSupport[calId];
2598
- if (cached === true) return;
2599
- if (cached === false) {
2600
- throw new Error(`RSCALE=${this.opts.rscale} is not supported by the current Temporal/Intl implementation`);
2601
- }
2602
- let supported = true;
2603
- try {
2604
- const probe = Temporal.ZonedDateTime.from("2000-01-01T00:00:00+00:00[UTC]").withCalendar(calId);
2605
- void probe.year;
2606
- void probe.monthCode;
2607
- void probe.day;
2608
- } catch (e) {
2609
- supported = false;
2610
- }
2611
- _RRuleTemporal.rscaleCalendarSupport[calId] = supported;
2612
- if (!supported) {
2613
- throw new Error(`RSCALE=${this.opts.rscale} is not supported by the current Temporal/Intl implementation`);
2614
- }
2615
- }
2616
- pad2(n) {
2617
- return String(n).padStart(2, "0");
2618
- }
2619
- monthMatchesToken(monthCode, token) {
2620
- if (typeof token === "number") {
2621
- return monthCode === `M${this.pad2(token)}`;
2622
- }
2623
- if (/^\d+L$/i.test(token)) {
2624
- const n = parseInt(token, 10);
2625
- return monthCode === `M${this.pad2(n)}L`;
2626
- }
2627
- return false;
2628
- }
2629
- monthsOfYear(calId, year) {
2630
- const out = [];
2631
- for (let m = 1; m <= 20; m++) {
2632
- try {
2633
- const d = Temporal.PlainDate.from({ calendar: calId, year, month: m, day: 1 });
2634
- out.push(d);
2635
- } catch (e) {
2636
- break;
2637
- }
2638
- }
2639
- return out;
2640
- }
2641
- startOfYear(calId, year) {
2642
- return Temporal.PlainDate.from({ calendar: calId, year, month: 1, day: 1 });
2643
- }
2644
- endOfYear(calId, year) {
2645
- return this.startOfYear(calId, year + 1).subtract({ days: 1 });
2646
- }
2647
- rscaleFirstWeekStart(calId, year, wkst) {
2648
- const jan4 = Temporal.PlainDate.from({ calendar: calId, year, month: 1, day: 4 });
2649
- const delta = (jan4.dayOfWeek - wkst + 7) % 7;
2650
- return jan4.subtract({ days: delta });
2651
- }
2652
- rscaleLastWeekCount(calId, year, wkst) {
2653
- const firstWeekStart = this.rscaleFirstWeekStart(calId, year, wkst);
2654
- const lastDay = this.endOfYear(calId, year);
2655
- const diffDays = lastDay.since(firstWeekStart).days;
2656
- return Math.floor(diffDays / 7) + 1;
2657
- }
2658
- lastDayOfMonth(pd) {
2659
- return pd.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
2660
- }
2661
- buildZdtFromPlainDate(pd) {
2662
- const t = this.originalDtstart;
2663
- const pdt = Temporal.PlainDateTime.from({
2664
- calendar: pd.calendarId,
2665
- year: pd.year,
2666
- month: pd.month,
2667
- day: pd.day,
2668
- hour: t.hour,
2669
- minute: t.minute,
2670
- second: t.second
2671
- });
2672
- return pdt.toZonedDateTime(this.tzid);
2673
- }
2674
- rscaleMatchesByYearDay(calId, pd) {
2675
- const list = this.opts.byYearDay;
2676
- if (!list || list.length === 0) return true;
2677
- const last = this.endOfYear(calId, pd.year).dayOfYear;
2678
- return list.some((d) => d > 0 ? pd.dayOfYear === d : pd.dayOfYear === last + d + 1);
2679
- }
2680
- rscaleMatchesByWeekNo(calId, pd) {
2681
- const list = this.opts.byWeekNo;
2682
- if (!list || list.length === 0) return true;
2683
- const dayMap = weekdayToIsoDay;
2684
- const wkst = dayMap[this.opts.wkst || "MO"];
2685
- const weekStart = pd.subtract({ days: (pd.dayOfWeek - wkst + 7) % 7 });
2686
- const thursday = weekStart.add({ days: (4 - wkst + 7) % 7 });
2687
- const weekYear = thursday.year;
2688
- const firstStart = this.rscaleFirstWeekStart(calId, weekYear, wkst);
2689
- const lastWeek = this.rscaleLastWeekCount(calId, weekYear, wkst);
2690
- const idx = Math.floor(pd.since(firstStart).days / 7) + 1;
2691
- return list.some((wn) => wn > 0 ? idx === wn : idx === lastWeek + wn + 1);
2692
- }
2693
- rscaleMatchesByMonth(calId, pd) {
2694
- const tokens = this.opts.byMonth;
2695
- if (!tokens || tokens.length === 0) return true;
2696
- return tokens.some((tok) => this.monthMatchesToken(pd.monthCode, tok));
2697
- }
2698
- rscaleMatchesByMonthDay(pd) {
2699
- const list = this.opts.byMonthDay;
2700
- if (!list || list.length === 0) return true;
2701
- const last = pd.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
2702
- const value = pd.day;
2703
- return list.some((d) => d > 0 ? value === d : value === last + d + 1);
2704
- }
2705
- rscaleMatchesByDayBasic(pd) {
2706
- const byDay = this.opts.byDay;
2707
- if (!byDay || byDay.length === 0) return true;
2708
- const dayMap = weekdayToIsoDay;
2709
- const tokens = byDay.map((tok) => extractWeekdayToken(tok)).filter((x) => x !== null);
2710
- if (tokens.length === 0) return true;
2711
- return tokens.some((wd) => dayMap[wd] === pd.dayOfWeek);
2712
- }
2713
- rscaleDateMatches(calId, pd) {
2714
- return this.rscaleMatchesByMonth(calId, pd) && this.rscaleMatchesByYearDay(calId, pd) && this.rscaleMatchesByWeekNo(calId, pd) && this.rscaleMatchesByMonthDay(pd) && this.rscaleMatchesByDayBasic(pd);
2715
- }
2716
- applySkipForDay(calId, year, monthStart, targetDay) {
2717
- const last = this.lastDayOfMonth(monthStart);
2718
- const skip = this.opts.skip || "OMIT";
2719
- if (targetDay >= 1 && targetDay <= last) {
2720
- return monthStart.with({ day: targetDay });
2721
- }
2722
- if (skip === "BACKWARD") {
2723
- return monthStart.with({ day: last });
2724
- }
2725
- if (skip === "FORWARD") {
2726
- const nextMonthStart = monthStart.add({ months: 1 });
2727
- return nextMonthStart.with({ day: 1 });
2728
- }
2729
- return null;
2730
- }
2731
- generateMonthlyOccurrencesRscale(calId, year, monthStart) {
2732
- const occs = [];
2733
- const byMonthDay = this.opts.byMonthDay;
2734
- const byDay = this.opts.byDay;
2735
- if (!byDay && !byMonthDay) {
2736
- const targetDay = this.originalDtstart.withCalendar(calId).day;
2737
- const pd = this.applySkipForDay(calId, year, monthStart, targetDay);
2738
- if (pd) occs.push(this.buildZdtFromPlainDate(pd));
2739
- return occs;
2740
- }
2741
- const addZ = (pd) => {
2742
- occs.push(this.buildZdtFromPlainDate(pd));
2743
- };
2744
- const last = this.lastDayOfMonth(monthStart);
2745
- const resolveDay = (d) => d > 0 ? d : last + d + 1;
2746
- if (byMonthDay && byMonthDay.length > 0) {
2747
- for (const raw of byMonthDay) {
2748
- const dayNum = resolveDay(raw);
2749
- const pd = this.applySkipForDay(calId, year, monthStart, dayNum);
2750
- if (pd) addZ(pd);
2751
- }
2752
- }
2753
- if (byDay && byDay.length > 0) {
2754
- const dayMap = weekdayToIsoDay;
2755
- const buckets = {};
2756
- let cur = monthStart;
2757
- while (cur.month === monthStart.month && cur.year === monthStart.year) {
2758
- const wd = cur.dayOfWeek;
2759
- (buckets[wd] || (buckets[wd] = [])).push(cur);
2760
- cur = cur.add({ days: 1 });
2761
- }
2762
- for (const tok of byDay) {
2763
- const parsed = parseByDayToken(tok);
2764
- if (!parsed) continue;
2765
- const ord = parsed.ord;
2766
- const wd = dayMap[parsed.weekday];
2767
- const list = buckets[wd] || [];
2768
- if (list.length === 0) continue;
2769
- if (ord === 0) {
2770
- for (const pd of list) addZ(pd);
2771
- } else {
2772
- const idx = ord > 0 ? ord - 1 : list.length + ord;
2773
- const pd = list[idx];
2774
- if (pd) addZ(pd);
2775
- }
2776
- }
2777
- }
2778
- return this.applyBySetPos(occs).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2779
- }
2780
- _allRscaleNonGregorian(iterator) {
2781
- var _a, _b, _c, _d, _e, _f, _g;
2782
- const calId = this.getRscaleCalendarId();
2783
- if (!calId) return this._allFallback(iterator);
2784
- this.assertRscaleCalendarSupported(calId);
2785
- const dates = [];
2786
- let iterationCount = 0;
2787
- const start = this.originalDtstart;
2788
- const seed = start.withCalendar(calId);
2789
- const interval = (_a = this.opts.interval) != null ? _a : 1;
2790
- if (!this.addDtstartIfNeeded(dates, iterator)) {
2791
- return this.applyCountLimitAndMergeRDates(dates, iterator);
2792
- }
2793
- if (this.opts.freq === "YEARLY") {
2794
- let yearOffset = 0;
2795
- while (true) {
2796
- if (++iterationCount > this.maxIterations) {
2797
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
2798
- }
2799
- const tgtYear = seed.year + yearOffset * interval;
2800
- let occs = [];
2801
- const monthsTokens = this.opts.byMonth;
2802
- const months = this.monthsOfYear(calId, tgtYear);
2803
- const dayMap = weekdayToIsoDay;
2804
- const wkst = dayMap[this.opts.wkst || "MO"];
2805
- if (this.opts.byWeekNo && this.opts.byWeekNo.length > 0) {
2806
- const firstStart = this.rscaleFirstWeekStart(calId, tgtYear, wkst);
2807
- const lastWeek = this.rscaleLastWeekCount(calId, tgtYear, wkst);
2808
- const tokens = ((_b = this.opts.byDay) == null ? void 0 : _b.length) ? this.opts.byDay.map((tok) => extractWeekdayToken(tok)).filter((day) => day !== null) : [Object.entries(dayMap).find(([, d]) => d === this.originalDtstart.dayOfWeek)[0]];
2809
- for (const wn of this.opts.byWeekNo) {
2810
- let idx = wn > 0 ? wn - 1 : lastWeek + wn;
2811
- if (idx < 0 || idx >= lastWeek) continue;
2812
- const weekStart = firstStart.add({ weeks: idx });
2813
- for (const tok of tokens) {
2814
- const targetDow = dayMap[tok];
2815
- const pd = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
2816
- if (monthsTokens && monthsTokens.length > 0) {
2817
- if (!monthsTokens.some((t) => this.monthMatchesToken(pd.monthCode, t))) continue;
2818
- }
2819
- if (this.opts.byYearDay && this.opts.byYearDay.length > 0) {
2820
- const lastDay = this.endOfYear(calId, tgtYear).dayOfYear;
2821
- const matches = this.opts.byYearDay.some((d) => {
2822
- const target = d > 0 ? d : lastDay + d + 1;
2823
- return pd.dayOfYear === target;
2824
- });
2825
- if (!matches) continue;
2826
- }
2827
- occs.push(this.buildZdtFromPlainDate(pd));
2828
- }
2829
- }
2830
- } else if (this.opts.byYearDay && this.opts.byYearDay.length > 0) {
2831
- const startOfYear = this.startOfYear(calId, tgtYear);
2832
- const lastDay = this.endOfYear(calId, tgtYear).dayOfYear;
2833
- for (const d of this.opts.byYearDay) {
2834
- const target = d > 0 ? d : lastDay + d + 1;
2835
- if (target < 1 || target > lastDay) continue;
2836
- let pd = startOfYear.add({ days: target - 1 });
2837
- if (monthsTokens && monthsTokens.length > 0) {
2838
- if (!monthsTokens.some((t) => this.monthMatchesToken(pd.monthCode, t))) continue;
2839
- }
2840
- occs.push(this.buildZdtFromPlainDate(pd));
2841
- }
2842
- } else if (!monthsTokens || monthsTokens.length === 0) {
2843
- try {
2844
- const pd = Temporal.PlainDate.from({
2845
- calendar: calId,
2846
- year: tgtYear,
2847
- monthCode: seed.monthCode,
2848
- day: seed.day
2849
- });
2850
- occs.push(this.buildZdtFromPlainDate(pd));
2851
- } catch (e) {
2852
- const skip = this.opts.skip || "OMIT";
2853
- if (skip === "FORWARD" || skip === "BACKWARD") {
2854
- const mapped = seed.with({ year: tgtYear });
2855
- const adjusted = skip === "BACKWARD" ? mapped.subtract({ days: 1 }) : mapped;
2856
- occs.push(adjusted.withCalendar("iso8601"));
2857
- }
2858
- }
2859
- } else {
2860
- const monthStarts = months.filter((m) => monthsTokens.some((tok) => this.monthMatchesToken(m.monthCode, tok)));
2861
- for (const ms of monthStarts) {
2862
- occs.push(...this.generateMonthlyOccurrencesRscale(calId, tgtYear, ms));
2863
- }
2864
- }
2865
- if (occs.length > 0) {
2866
- const expanded = occs.flatMap((z) => this.expandByTime(z));
2867
- const sorted = expanded.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2868
- const { shouldBreak } = this.processOccurrences(sorted, dates, start, iterator);
2869
- if (shouldBreak) break;
2870
- }
2871
- yearOffset++;
2872
- if (this.opts.until && tgtYear > this.opts.until.withCalendar(calId).year) break;
2873
- }
2874
- return this.applyCountLimitAndMergeRDates(dates, iterator);
2875
- }
2876
- if (this.opts.freq === "WEEKLY") {
2877
- const dayMap = weekdayToIsoDay;
2878
- const wkst = dayMap[this.opts.wkst || "MO"];
2879
- const tokens = ((_c = this.opts.byDay) == null ? void 0 : _c.length) ? this.opts.byDay.map((tok) => extractWeekdayToken(tok)).filter((day) => day !== null) : [Object.entries(dayMap).find(([, d]) => d === this.originalDtstart.dayOfWeek)[0]];
2880
- let weekStart = seed.toPlainDate().subtract({ days: (seed.dayOfWeek - wkst + 7) % 7 });
2881
- while (true) {
2882
- if (++iterationCount > this.maxIterations) {
2883
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
2884
- }
2885
- const occs = [];
2886
- for (const tok of tokens) {
2887
- const targetDow = dayMap[tok];
2888
- const pd = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
2889
- if (Temporal.ZonedDateTime.compare(this.buildZdtFromPlainDate(pd), this.originalDtstart) < 0) {
2890
- continue;
2891
- }
2892
- if (this.opts.byWeekNo && this.opts.byWeekNo.length > 0) {
2893
- const thursday = weekStart.add({ days: (4 - wkst + 7) % 7 });
2894
- const weekYear = thursday.year;
2895
- const firstStart = this.rscaleFirstWeekStart(calId, weekYear, wkst);
2896
- const lastWeek = this.rscaleLastWeekCount(calId, weekYear, wkst);
2897
- const idx = Math.floor(pd.since(firstStart).days / 7) + 1;
2898
- const match = this.opts.byWeekNo.some((wn) => wn > 0 ? idx === wn : idx === lastWeek + wn + 1);
2899
- if (!match) continue;
2900
- }
2901
- if (this.opts.byYearDay && this.opts.byYearDay.length > 0) {
2902
- const last = this.endOfYear(calId, pd.year).dayOfYear;
2903
- const match = this.opts.byYearDay.some((d) => d > 0 ? pd.dayOfYear === d : pd.dayOfYear === last + d + 1);
2904
- if (!match) continue;
2905
- }
2906
- const monthsTokens = this.opts.byMonth;
2907
- if (monthsTokens && monthsTokens.length > 0) {
2908
- if (!monthsTokens.some((t) => this.monthMatchesToken(pd.monthCode, t))) continue;
2909
- }
2910
- occs.push(this.buildZdtFromPlainDate(pd));
2911
- }
2912
- if (occs.length) {
2913
- const expanded = occs.flatMap((z) => this.expandByTime(z));
2914
- const sorted = expanded.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2915
- const { shouldBreak } = this.processOccurrences(sorted, dates, start, iterator);
2916
- if (shouldBreak) return this.applyCountLimitAndMergeRDates(dates, iterator);
2917
- }
2918
- weekStart = weekStart.add({ weeks: (_d = this.opts.interval) != null ? _d : 1 });
2919
- if (this.opts.until) {
2920
- const z = this.buildZdtFromPlainDate(weekStart.add({ days: 6 }));
2921
- if (Temporal.ZonedDateTime.compare(z, this.opts.until) > 0) break;
2922
- }
2923
- }
2924
- return this.applyCountLimitAndMergeRDates(dates, iterator);
2925
- }
2926
- if (this.opts.freq === "MONTHLY") {
2927
- let cursor = seed.toPlainDate().with({ day: 1 });
2928
- while (true) {
2929
- if (++iterationCount > this.maxIterations) {
2930
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
2931
- }
2932
- const year = cursor.year;
2933
- const monthStart = cursor;
2934
- let proceed = true;
2935
- const monthsTokens = this.opts.byMonth;
2936
- if (monthsTokens && monthsTokens.length > 0) {
2937
- proceed = monthsTokens.some((tok) => this.monthMatchesToken(monthStart.monthCode, tok));
2938
- }
2939
- if (proceed) {
2940
- const occs = this.generateMonthlyOccurrencesRscale(calId, year, monthStart);
2941
- const expanded = occs.flatMap((z) => this.expandByTime(z));
2942
- const sorted = expanded.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
2943
- const { shouldBreak } = this.processOccurrences(sorted, dates, start, iterator);
2944
- if (shouldBreak) break;
2945
- }
2946
- cursor = cursor.add({ months: (_e = this.opts.interval) != null ? _e : 1 });
2947
- if (this.opts.until) {
2948
- const z = this.buildZdtFromPlainDate(cursor);
2949
- if (Temporal.ZonedDateTime.compare(z, this.opts.until) > 0) break;
2950
- }
2951
- }
2952
- return this.applyCountLimitAndMergeRDates(dates, iterator);
2953
- }
2954
- if (this.opts.freq === "DAILY") {
2955
- let pd = seed.toPlainDate();
2956
- while (true) {
2957
- if (++iterationCount > this.maxIterations) {
2958
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
2959
- }
2960
- if (this.rscaleDateMatches(calId, pd)) {
2961
- const base = this.buildZdtFromPlainDate(pd);
2962
- let occs = this.expandByTime(base);
2963
- occs = this.applyBySetPos(occs);
2964
- const { shouldBreak } = this.processOccurrences(occs, dates, start, iterator);
2965
- if (shouldBreak) break;
2966
- }
2967
- pd = pd.add({ days: (_f = this.opts.interval) != null ? _f : 1 });
2968
- if (this.opts.until) {
2969
- const z = this.buildZdtFromPlainDate(pd);
2970
- if (Temporal.ZonedDateTime.compare(z, this.opts.until) > 0) break;
2971
- }
2972
- }
2973
- return this.applyCountLimitAndMergeRDates(dates, iterator);
2974
- }
2975
- if (this.opts.freq === "HOURLY" || this.opts.freq === "MINUTELY") {
2976
- const unit = this.opts.freq === "HOURLY" ? "hour" : "minute";
2977
- const unitMs = this.opts.freq === "HOURLY" ? 36e5 : 6e4;
2978
- const interval2 = (_g = this.opts.interval) != null ? _g : 1;
2979
- let pd = seed.toPlainDate();
2980
- const startInstantMs = this.originalDtstart.toInstant().epochMilliseconds;
2981
- while (true) {
2982
- if (++iterationCount > this.maxIterations) {
2983
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
2984
- }
2985
- if (this.rscaleDateMatches(calId, pd)) {
2986
- const base = this.buildZdtFromPlainDate(pd);
2987
- let occs = this.expandByTime(base);
2988
- occs = occs.filter((occ) => {
2989
- const delta = occ.toInstant().epochMilliseconds - startInstantMs;
2990
- const steps = Math.floor(delta / unitMs);
2991
- return steps % interval2 === 0;
2992
- });
2993
- const { shouldBreak } = this.processOccurrences(occs, dates, start, iterator);
2994
- if (shouldBreak) break;
2995
- }
2996
- pd = pd.add({ days: 1 });
2997
- if (this.opts.until) {
2998
- const z = this.buildZdtFromPlainDate(pd);
2999
- if (Temporal.ZonedDateTime.compare(z, this.opts.until) > 0) break;
3000
- }
3001
- }
3002
- return this.applyCountLimitAndMergeRDates(dates, iterator);
3003
- }
3004
- return this._allFallback(iterator);
3005
- }
3006
- };
3007
- _RRuleTemporal.rscaleCalendarSupport = {};
3008
- var RRuleTemporal = _RRuleTemporal;
3009
-
3010
- export {
3011
- allowedFreq,
3012
- allowedWeekdays,
3013
- weekdayToIsoDay,
3014
- RRuleTemporal
3015
- };