rrule-temporal 1.1.4 → 1.1.6

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,1395 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
- var __hasOwnProp = Object.prototype.hasOwnProperty;
4
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
7
- for (var prop in b || (b = {}))
8
- if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
10
- if (__getOwnPropSymbols)
11
- for (var prop of __getOwnPropSymbols(b)) {
12
- if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- }
15
- return a;
16
- };
17
-
18
- // src/index.ts
19
- import { Temporal } from "@js-temporal/polyfill";
20
- function unfoldLine(foldedLine) {
21
- return foldedLine.replace(/\r?\n[ \t]/g, "");
22
- }
23
- function parseIcsDateTime(dateStr, tzid, valueType) {
24
- const isDate = valueType === "DATE" || !dateStr.includes("T");
25
- if (isDate) {
26
- const isoDate = `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
27
- return Temporal.PlainDate.from(isoDate).toZonedDateTime({ timeZone: tzid });
28
- }
29
- if (/Z$/.test(dateStr)) {
30
- const iso = `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}T${dateStr.slice(9, 15)}Z`;
31
- return Temporal.Instant.from(iso).toZonedDateTimeISO(tzid || "UTC");
32
- } else {
33
- const isoDate = `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}T${dateStr.slice(9)}`;
34
- return Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid);
35
- }
36
- }
37
- function parseDateValues(dateValues, tzid, valueType) {
38
- const dates = [];
39
- for (const dateValue of dateValues) {
40
- dates.push(parseIcsDateTime(dateValue, tzid, valueType));
41
- }
42
- return dates;
43
- }
44
- function parseDateLines(lines, linePrefix, defaultTzid) {
45
- const dates = [];
46
- const regex = new RegExp(`^${linePrefix}(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)`, "i");
47
- for (const line of lines) {
48
- const match = line.match(regex);
49
- if (match) {
50
- const [, valueType, tzid, dateValuesStr] = match;
51
- const timezone = tzid || defaultTzid;
52
- const dateValues = dateValuesStr.split(",");
53
- dates.push(...parseDateValues(dateValues, timezone, valueType));
54
- }
55
- }
56
- return dates;
57
- }
58
- function parseRRuleString(input, targetTimezone) {
59
- var _a;
60
- const unfoldedInput = unfoldLine(input).trim();
61
- let dtstart;
62
- let tzid = "UTC";
63
- let rruleLine;
64
- let exDate = [];
65
- let rDate = [];
66
- if (/^DTSTART/im.test(unfoldedInput)) {
67
- const lines = unfoldedInput.split(/\s+/);
68
- const dtLine = lines.find((line) => line.match(/^DTSTART/i));
69
- const rrLine = lines.find((line) => line.match(/^RRULE:/i));
70
- const exLines = lines.filter((line) => line.match(/^EXDATE/i));
71
- const rLines = lines.filter((line) => line.match(/^RDATE/i));
72
- const dtMatch = dtLine.match(/DTSTART(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)/i);
73
- if (!dtMatch) throw new Error("Invalid DTSTART in ICS snippet");
74
- const [, valueType, dtTzid, dtValue] = dtMatch;
75
- tzid = (_a = dtTzid != null ? dtTzid : targetTimezone) != null ? _a : tzid;
76
- dtstart = parseIcsDateTime(dtValue, tzid, valueType);
77
- rruleLine = rrLine;
78
- exDate = parseDateLines(exLines, "EXDATE", tzid);
79
- rDate = parseDateLines(rLines, "RDATE", tzid);
80
- } else {
81
- throw new Error("dtstart required when parsing RRULE alone");
82
- }
83
- const parts = rruleLine ? rruleLine.replace(/^RRULE:/i, "").split(";") : [];
84
- const opts = {
85
- dtstart,
86
- tzid,
87
- exDate: exDate.length > 0 ? exDate : void 0,
88
- rDate: rDate.length > 0 ? rDate : void 0
89
- };
90
- for (const part of parts) {
91
- const [key, val] = part.split("=");
92
- if (!key) continue;
93
- switch (key.toUpperCase()) {
94
- case "FREQ":
95
- opts.freq = val.toUpperCase();
96
- break;
97
- case "INTERVAL":
98
- opts.interval = parseInt(val, 10);
99
- break;
100
- case "COUNT":
101
- opts.count = parseInt(val, 10);
102
- break;
103
- case "UNTIL": {
104
- opts.until = parseIcsDateTime(val, tzid || "UTC");
105
- if (!/Z$/.test(val) && tzid !== "UTC") {
106
- throw new Error("UNTIL rule part MUST always be specified as a date with UTC time");
107
- }
108
- break;
109
- }
110
- case "BYHOUR":
111
- opts.byHour = val.split(",").map((n) => parseInt(n, 10)).sort((a, b) => a - b);
112
- break;
113
- case "BYMINUTE":
114
- opts.byMinute = val.split(",").map((n) => parseInt(n, 10)).sort((a, b) => a - b);
115
- break;
116
- case "BYDAY":
117
- opts.byDay = val.split(",");
118
- break;
119
- case "BYMONTH":
120
- opts.byMonth = val.split(",").map((n) => parseInt(n, 10));
121
- break;
122
- case "BYMONTHDAY":
123
- opts.byMonthDay = val.split(",").map((n) => parseInt(n, 10));
124
- break;
125
- case "BYSECOND":
126
- opts.bySecond = val.split(",").map((n) => parseInt(n, 10)).sort((a, b) => a - b);
127
- break;
128
- case "BYYEARDAY":
129
- opts.byYearDay = val.split(",").map((n) => parseInt(n, 10));
130
- break;
131
- case "BYWEEKNO":
132
- opts.byWeekNo = val.split(",").map((n) => parseInt(n, 10));
133
- break;
134
- case "BYSETPOS":
135
- opts.bySetPos = val.split(",").map((n) => parseInt(n, 10));
136
- break;
137
- case "WKST":
138
- opts.wkst = val;
139
- break;
140
- }
141
- }
142
- return opts;
143
- }
144
- var RRuleTemporal = class _RRuleTemporal {
145
- constructor(params) {
146
- var _a, _b, _c, _d, _e;
147
- let manual;
148
- if ("rruleString" in params) {
149
- const parsed = parseRRuleString(params.rruleString, params.tzid);
150
- this.tzid = (_b = (_a = parsed.tzid) != null ? _a : params.tzid) != null ? _b : "UTC";
151
- this.originalDtstart = parsed.dtstart;
152
- manual = __spreadValues(__spreadValues({}, params), parsed);
153
- } else {
154
- manual = __spreadValues({}, params);
155
- if (typeof manual.dtstart === "string") {
156
- throw new Error("Manual dtstart must be a ZonedDateTime");
157
- }
158
- manual.tzid = manual.tzid || manual.dtstart.timeZoneId;
159
- this.tzid = manual.tzid;
160
- this.originalDtstart = manual.dtstart;
161
- }
162
- if (!manual.freq) throw new Error("RRULE must include FREQ");
163
- manual.interval = (_c = manual.interval) != null ? _c : 1;
164
- if (manual.interval <= 0) {
165
- throw new Error("Cannot create RRule: interval must be greater than 0");
166
- }
167
- if (manual.until && !(manual.until instanceof Temporal.ZonedDateTime)) {
168
- throw new Error("Manual until must be a ZonedDateTime");
169
- }
170
- this.opts = this.sanitizeOpts(manual);
171
- this.maxIterations = (_d = manual.maxIterations) != null ? _d : 1e4;
172
- this.includeDtstart = (_e = manual.includeDtstart) != null ? _e : false;
173
- }
174
- sanitizeNumericArray(arr, min, max, allowZero = false, sort = false) {
175
- if (!arr) return void 0;
176
- const sanitized = arr.filter((n) => Number.isInteger(n) && n >= min && n <= max && (allowZero || n !== 0));
177
- if (sanitized.length === 0) return void 0;
178
- return sort ? sanitized.sort((a, b) => a - b) : sanitized;
179
- }
180
- sanitizeOpts(opts) {
181
- const validDay = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/;
182
- if (opts.byDay) {
183
- opts.byDay = opts.byDay.filter((d) => validDay.test(d));
184
- if (opts.byDay.length === 0) delete opts.byDay;
185
- }
186
- opts.byMonth = this.sanitizeNumericArray(opts.byMonth, 1, 12, false, false);
187
- opts.byMonthDay = this.sanitizeNumericArray(opts.byMonthDay, -31, 31, false, false);
188
- opts.byYearDay = this.sanitizeNumericArray(opts.byYearDay, -366, 366, false, false);
189
- opts.byWeekNo = this.sanitizeNumericArray(opts.byWeekNo, -53, 53, false, false);
190
- opts.byHour = this.sanitizeNumericArray(opts.byHour, 0, 23, true, true);
191
- opts.byMinute = this.sanitizeNumericArray(opts.byMinute, 0, 59, true, true);
192
- opts.bySecond = this.sanitizeNumericArray(opts.bySecond, 0, 59, true, true);
193
- if (opts.bySetPos) {
194
- if (opts.bySetPos.some((p) => p === 0)) {
195
- throw new Error("bySetPos may not contain 0");
196
- }
197
- opts.bySetPos = this.sanitizeNumericArray(opts.bySetPos, -Infinity, Infinity, false, false);
198
- }
199
- return opts;
200
- }
201
- rawAdvance(zdt) {
202
- const { freq, interval } = this.opts;
203
- switch (freq) {
204
- case "DAILY":
205
- return zdt.add({ days: interval });
206
- case "WEEKLY":
207
- return zdt.add({ weeks: interval });
208
- case "MONTHLY":
209
- return zdt.add({ months: interval });
210
- case "YEARLY":
211
- return zdt.add({ years: interval });
212
- case "HOURLY": {
213
- const originalHour = zdt.hour;
214
- let next = zdt.add({ hours: interval });
215
- if (next.hour === originalHour && interval === 1) {
216
- next = next.add({ hours: interval });
217
- }
218
- return next;
219
- }
220
- case "MINUTELY":
221
- return zdt.add({ minutes: interval });
222
- case "SECONDLY":
223
- return zdt.add({ seconds: interval });
224
- default:
225
- throw new Error(`Unsupported FREQ: ${freq}`);
226
- }
227
- }
228
- /** Expand one base ZonedDateTime into all BYHOUR × BYMINUTE × BYSECOND
229
- * combinations, keeping chronological order. If the options are not
230
- * present the original date is returned unchanged.
231
- */
232
- expandByTime(base) {
233
- var _a, _b, _c;
234
- const hours = (_a = this.opts.byHour) != null ? _a : [base.hour];
235
- const minutes = (_b = this.opts.byMinute) != null ? _b : [base.minute];
236
- const seconds = (_c = this.opts.bySecond) != null ? _c : [base.second];
237
- const out = [];
238
- for (const h of hours) {
239
- for (const m of minutes) {
240
- for (const s of seconds) {
241
- out.push(base.with({ hour: h, minute: m, second: s }));
242
- }
243
- }
244
- }
245
- return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
246
- }
247
- nextCandidateSameDate(zdt) {
248
- const { freq, interval = 1, byHour, byMinute, bySecond } = this.opts;
249
- if (freq === "HOURLY" && byHour && byHour.length === 1) {
250
- return this.applyTimeOverride(zdt.add({ days: interval }));
251
- }
252
- if (freq === "MINUTELY" && byMinute && byMinute.length === 1) {
253
- return this.applyTimeOverride(zdt.add({ hours: interval }));
254
- }
255
- if (bySecond && bySecond.length > 1) {
256
- const idx = bySecond.indexOf(zdt.second);
257
- if (idx !== -1 && idx < bySecond.length - 1) {
258
- return zdt.with({ second: bySecond[idx + 1] });
259
- }
260
- }
261
- if (freq === "MINUTELY" && byHour && byHour.length > 1 && !byMinute) {
262
- const next = zdt.add({ minutes: interval });
263
- if (byHour.includes(next.hour)) {
264
- return next.with({ second: bySecond ? bySecond[0] : zdt.second });
265
- }
266
- const nextHour = byHour.find((h) => h > zdt.hour) || byHour[0];
267
- if (nextHour && nextHour > zdt.hour) {
268
- return zdt.with({ hour: nextHour, minute: 0, second: bySecond ? bySecond[0] : zdt.second });
269
- }
270
- return this.applyTimeOverride(zdt.add({ days: 1 }));
271
- }
272
- if (freq === "SECONDLY") {
273
- let next = zdt.add({ seconds: interval });
274
- if (bySecond && bySecond.length > 0) {
275
- const nextSecond = bySecond.find((s) => s > zdt.second);
276
- if (nextSecond !== void 0) {
277
- next = zdt.with({ second: nextSecond });
278
- } else {
279
- next = zdt.add({ minutes: 1 }).with({ second: bySecond[0] });
280
- }
281
- }
282
- if (byMinute && byMinute.length > 0 && !byMinute.includes(next.minute)) {
283
- const nextMinute = byMinute.find((m) => m > next.minute);
284
- if (nextMinute !== void 0) {
285
- next = next.with({ minute: nextMinute, second: bySecond ? bySecond[0] : 0 });
286
- } else {
287
- const nextHour = byHour ? byHour.find((h) => h > next.hour) : void 0;
288
- if (nextHour !== void 0) {
289
- next = next.with({ hour: nextHour, minute: byMinute[0], second: bySecond ? bySecond[0] : 0 });
290
- } else {
291
- next = this.applyTimeOverride(next.add({ days: 1 }));
292
- }
293
- }
294
- }
295
- if (byHour && byHour.length > 0 && !byHour.includes(next.hour)) {
296
- const nextHour = byHour.find((h) => h > next.hour);
297
- if (nextHour !== void 0) {
298
- next = next.with({ hour: nextHour, minute: byMinute ? byMinute[0] : 0, second: bySecond ? bySecond[0] : 0 });
299
- } else {
300
- next = this.applyTimeOverride(next.add({ days: 1 }));
301
- }
302
- }
303
- return next;
304
- }
305
- if (byMinute && byMinute.length > 1) {
306
- const idx = byMinute.indexOf(zdt.minute);
307
- if (idx !== -1 && idx < byMinute.length - 1) {
308
- return zdt.with({
309
- minute: byMinute[idx + 1],
310
- second: bySecond ? bySecond[0] : zdt.second
311
- });
312
- }
313
- if (freq === "MINUTELY" && idx === byMinute.length - 1) {
314
- if (byHour && byHour.length > 0) {
315
- const currentHourIdx = byHour.indexOf(zdt.hour);
316
- if (currentHourIdx !== -1 && currentHourIdx < byHour.length - 1) {
317
- return zdt.with({
318
- hour: byHour[currentHourIdx + 1],
319
- minute: byMinute[0],
320
- second: bySecond ? bySecond[0] : zdt.second
321
- });
322
- } else {
323
- return this.applyTimeOverride(zdt.add({ days: 1 }));
324
- }
325
- }
326
- return zdt.add({ hours: interval }).with({
327
- minute: byMinute[0],
328
- second: bySecond ? bySecond[0] : zdt.second
329
- });
330
- }
331
- }
332
- if (byHour && byHour.length > 1) {
333
- const idx = byHour.indexOf(zdt.hour);
334
- if (idx !== -1 && idx < byHour.length - 1) {
335
- return zdt.with({
336
- hour: byHour[idx + 1],
337
- minute: byMinute ? byMinute[0] : zdt.minute,
338
- second: bySecond ? bySecond[0] : zdt.second
339
- });
340
- }
341
- }
342
- if (freq === "HOURLY" && byHour && byHour.length > 1) {
343
- return this.applyTimeOverride(zdt.add({ days: 1 }));
344
- }
345
- return this.applyTimeOverride(this.rawAdvance(zdt));
346
- }
347
- applyTimeOverride(zdt) {
348
- const { byHour, byMinute, bySecond } = this.opts;
349
- let dt = zdt;
350
- if (byHour) dt = dt.with({ hour: byHour[0] });
351
- if (byMinute) dt = dt.with({ minute: byMinute[0] });
352
- if (bySecond) dt = dt.with({ second: bySecond[0] });
353
- return dt;
354
- }
355
- computeFirst() {
356
- var _a, _b, _c, _d;
357
- let zdt = this.originalDtstart;
358
- if (((_a = this.opts.byWeekNo) == null ? void 0 : _a.length) && ["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq)) {
359
- let targetWeek = this.opts.byWeekNo[0];
360
- let targetYear = zdt.year;
361
- while (targetYear <= zdt.year + 10) {
362
- const jan1 = zdt.with({ year: targetYear, month: 1, day: 1 });
363
- const dec31 = zdt.with({ year: targetYear, month: 12, day: 31 });
364
- let hasTargetWeek = false;
365
- if (targetWeek > 0) {
366
- let maxWeek = 52;
367
- if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
368
- maxWeek = 53;
369
- }
370
- hasTargetWeek = targetWeek <= maxWeek;
371
- } else {
372
- let maxWeek = 52;
373
- if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
374
- maxWeek = 53;
375
- }
376
- hasTargetWeek = -targetWeek <= maxWeek;
377
- }
378
- if (hasTargetWeek) {
379
- const firstThursday = jan1.add({ days: (4 - jan1.dayOfWeek + 7) % 7 });
380
- let weekStart;
381
- if (targetWeek > 0) {
382
- weekStart = firstThursday.subtract({ days: 3 }).add({ weeks: targetWeek - 1 });
383
- } else {
384
- const lastWeek = jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4 ? 53 : 52;
385
- weekStart = firstThursday.subtract({ days: 3 }).add({ weeks: lastWeek + targetWeek });
386
- }
387
- if ((_b = this.opts.byDay) == null ? void 0 : _b.length) {
388
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
389
- const targetDays = this.opts.byDay.map((tok) => {
390
- var _a2;
391
- return (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
392
- }).filter(Boolean).map((day) => dayMap[day]).filter(Boolean);
393
- if (targetDays.length) {
394
- const candidates = targetDays.map((dayOfWeek) => {
395
- const delta = (dayOfWeek - weekStart.dayOfWeek + 7) % 7;
396
- return weekStart.add({ days: delta });
397
- });
398
- const firstCandidate = candidates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b))[0];
399
- if (firstCandidate && Temporal.ZonedDateTime.compare(firstCandidate, this.originalDtstart) >= 0) {
400
- zdt = firstCandidate;
401
- break;
402
- }
403
- }
404
- } else {
405
- if (Temporal.ZonedDateTime.compare(weekStart, this.originalDtstart) >= 0) {
406
- zdt = weekStart;
407
- break;
408
- }
409
- }
410
- }
411
- targetYear++;
412
- }
413
- }
414
- if (((_c = this.opts.byDay) == null ? void 0 : _c.length) && !this.opts.byWeekNo) {
415
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
416
- const hasOrdinalTokens = this.opts.byDay.some((tok) => /^[+-]?\d/.test(tok));
417
- if (hasOrdinalTokens && this.opts.byMonth && (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY")) {
418
- const months = [...this.opts.byMonth].sort((a, b) => a - b);
419
- let foundFirst = false;
420
- for (let year = zdt.year; year <= zdt.year + 10 && !foundFirst; year++) {
421
- for (const month of months) {
422
- if (year === zdt.year && month < zdt.month) continue;
423
- const monthSample = zdt.with({ year, month, day: 1 });
424
- const monthlyOccs = this.generateMonthlyOccurrences(monthSample);
425
- for (const occ of monthlyOccs) {
426
- if (Temporal.ZonedDateTime.compare(occ, zdt) >= 0) {
427
- if (!occ.toPlainDate().equals(zdt.toPlainDate())) {
428
- zdt = this.applyTimeOverride(occ.with({ hour: 0, minute: 0, second: 0 }));
429
- } else {
430
- zdt = occ;
431
- }
432
- foundFirst = true;
433
- break;
434
- }
435
- }
436
- if (foundFirst) break;
437
- }
438
- }
439
- } else {
440
- let deltas = [];
441
- if (["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq) && this.opts.byDay.every((tok) => /^[A-Z]{2}$/.test(tok))) {
442
- deltas = this.opts.byDay.map((tok) => (dayMap[tok] - zdt.dayOfWeek + 7) % 7);
443
- } else {
444
- deltas = this.opts.byDay.map((tok) => {
445
- var _a2;
446
- const wdTok = (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
447
- return wdTok ? (dayMap[wdTok] - zdt.dayOfWeek + 7) % 7 : null;
448
- }).filter((d) => d !== null);
449
- }
450
- if (deltas.length) {
451
- zdt = zdt.add({ days: Math.min(...deltas) });
452
- }
453
- }
454
- }
455
- const { byHour, byMinute, bySecond } = this.opts;
456
- if (this.opts.freq === "HOURLY" && !byHour && Temporal.ZonedDateTime.compare(
457
- zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
458
- this.originalDtstart
459
- ) > 0) {
460
- zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
461
- }
462
- if (this.opts.freq === "MINUTELY" && !byMinute && Temporal.ZonedDateTime.compare(
463
- zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
464
- this.originalDtstart
465
- ) > 0) {
466
- zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
467
- }
468
- if (this.opts.freq === "SECONDLY" && ((_d = this.opts.byWeekNo) == null ? void 0 : _d.length) && !bySecond && Temporal.ZonedDateTime.compare(
469
- zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
470
- this.originalDtstart
471
- ) > 0) {
472
- zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
473
- }
474
- if (byHour || byMinute || bySecond) {
475
- const candidates = this.expandByTime(zdt);
476
- for (const candidate of candidates) {
477
- if (Temporal.ZonedDateTime.compare(candidate, this.originalDtstart) >= 0) {
478
- return candidate;
479
- }
480
- }
481
- zdt = this.applyTimeOverride(this.rawAdvance(zdt));
482
- }
483
- return zdt;
484
- }
485
- // --- NEW: constraint checks ---
486
- // 2) Replace your matchesByDay with this:
487
- matchesByDay(zdt) {
488
- const { byDay, freq } = this.opts;
489
- if (!byDay) return true;
490
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
491
- for (const token of byDay) {
492
- const m = token.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
493
- if (!m) continue;
494
- const ord = m[1] ? parseInt(m[1], 10) : 0;
495
- const weekday = m[2];
496
- if (!weekday) continue;
497
- const wd = dayMap[weekday];
498
- if (freq === "DAILY") {
499
- if (zdt.dayOfWeek === wd) return true;
500
- continue;
501
- }
502
- if (ord === 0) {
503
- if (zdt.dayOfWeek === wd) return true;
504
- continue;
505
- }
506
- const month = zdt.month;
507
- let dt = zdt.with({ day: 1 });
508
- const candidates = [];
509
- while (dt.month === month) {
510
- if (dt.dayOfWeek === wd) candidates.push(dt.day);
511
- dt = dt.add({ days: 1 });
512
- }
513
- const idx = ord > 0 ? ord - 1 : candidates.length + ord;
514
- if (candidates[idx] === zdt.day) return true;
515
- }
516
- return false;
517
- }
518
- matchesByMonth(zdt) {
519
- const { byMonth } = this.opts;
520
- if (!byMonth) return true;
521
- return byMonth.includes(zdt.month);
522
- }
523
- matchesNumericConstraint(value, constraints, maxPositiveValue) {
524
- return constraints.some((c) => {
525
- const target = c > 0 ? c : maxPositiveValue + c + 1;
526
- return value === target;
527
- });
528
- }
529
- matchesByMonthDay(zdt) {
530
- const { byMonthDay } = this.opts;
531
- if (!byMonthDay) return true;
532
- const lastDay = zdt.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
533
- return this.matchesNumericConstraint(zdt.day, byMonthDay, lastDay);
534
- }
535
- matchesByHour(zdt) {
536
- const { byHour } = this.opts;
537
- if (!byHour) return true;
538
- if (byHour.includes(zdt.hour)) {
539
- return true;
540
- }
541
- for (const h of byHour) {
542
- const intendedTime = zdt.with({ hour: h });
543
- if (intendedTime.hour === zdt.hour) {
544
- return true;
545
- }
546
- }
547
- return false;
548
- }
549
- matchesByMinute(zdt) {
550
- const { byMinute } = this.opts;
551
- if (!byMinute) return true;
552
- return byMinute.includes(zdt.minute);
553
- }
554
- matchesBySecond(zdt) {
555
- const { bySecond } = this.opts;
556
- if (!bySecond) return true;
557
- return bySecond.includes(zdt.second);
558
- }
559
- matchesAll(zdt) {
560
- return this.matchesByDay(zdt) && this.matchesByMonth(zdt) && this.matchesByMonthDay(zdt) && this.matchesByYearDay(zdt) && this.matchesByWeekNo(zdt) && this.matchesByHour(zdt) && this.matchesByMinute(zdt) && this.matchesBySecond(zdt);
561
- }
562
- matchesByYearDay(zdt) {
563
- const { byYearDay } = this.opts;
564
- if (!byYearDay) return true;
565
- const dayOfYear = zdt.dayOfYear;
566
- const last = zdt.with({ month: 12, day: 31 }).dayOfYear;
567
- return this.matchesNumericConstraint(dayOfYear, byYearDay, last);
568
- }
569
- getIsoWeekInfo(zdt) {
570
- const thursday = zdt.add({ days: 4 - zdt.dayOfWeek });
571
- const year = thursday.year;
572
- const jan1 = zdt.with({ year, month: 1, day: 1 });
573
- const firstThursday = jan1.add({ days: (4 - jan1.dayOfWeek + 7) % 7 });
574
- const diffDays = thursday.toPlainDate().since(firstThursday.toPlainDate()).days;
575
- const week = Math.floor(diffDays / 7) + 1;
576
- return { week, year };
577
- }
578
- matchesByWeekNo(zdt) {
579
- const { byWeekNo } = this.opts;
580
- if (!byWeekNo) return true;
581
- const { week, year } = this.getIsoWeekInfo(zdt);
582
- const jan1 = zdt.with({ year, month: 1, day: 1 });
583
- const dec31 = zdt.with({ year, month: 12, day: 31 });
584
- let lastWeek = 52;
585
- if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
586
- lastWeek = 53;
587
- }
588
- return byWeekNo.some((wn) => {
589
- if (wn > 0) {
590
- return week === wn;
591
- } else {
592
- return week === lastWeek + wn + 1;
593
- }
594
- });
595
- }
596
- options() {
597
- return this.opts;
598
- }
599
- addDtstartIfNeeded(dates, iterator) {
600
- if (this.includeDtstart && !this.matchesAll(this.originalDtstart)) {
601
- if (iterator && !iterator(this.originalDtstart, dates.length)) {
602
- return false;
603
- }
604
- dates.push(this.originalDtstart);
605
- if (this.shouldBreakForCountLimit(dates.length)) {
606
- return false;
607
- }
608
- }
609
- return true;
610
- }
611
- processOccurrences(occs, dates, start, iterator, extraFilters) {
612
- let shouldBreak = false;
613
- for (const occ of occs) {
614
- if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
615
- if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
616
- shouldBreak = true;
617
- break;
618
- }
619
- if (extraFilters && !extraFilters(occ)) {
620
- continue;
621
- }
622
- if (iterator && !iterator(occ, dates.length)) {
623
- shouldBreak = true;
624
- break;
625
- }
626
- dates.push(occ);
627
- if (this.shouldBreakForCountLimit(dates.length)) {
628
- shouldBreak = true;
629
- break;
630
- }
631
- }
632
- return { shouldBreak };
633
- }
634
- /**
635
- * Returns all occurrences of the rule.
636
- * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
637
- * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
638
- */
639
- all(iterator) {
640
- var _a;
641
- if (!this.opts.count && !this.opts.until && !iterator) {
642
- throw new Error("all() requires iterator when no COUNT/UNTIL");
643
- }
644
- const dates = [];
645
- let iterationCount = 0;
646
- if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
647
- const start = this.originalDtstart;
648
- if (!this.addDtstartIfNeeded(dates, iterator)) {
649
- return this.applyCountLimitAndMergeRDates(dates, iterator);
650
- }
651
- let monthCursor = start.with({ day: 1 });
652
- while (true) {
653
- if (++iterationCount > this.maxIterations) {
654
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
655
- }
656
- let occs = this.generateMonthlyOccurrences(monthCursor);
657
- occs = this.applyBySetPos(occs);
658
- if (monthCursor.month === start.month && occs.some((o) => Temporal.ZonedDateTime.compare(o, start) < 0) && occs.some((o) => Temporal.ZonedDateTime.compare(o, start) === 0)) {
659
- monthCursor = monthCursor.add({ months: this.opts.interval });
660
- continue;
661
- }
662
- const { shouldBreak } = this.processOccurrences(occs, dates, start, iterator);
663
- if (shouldBreak) {
664
- break;
665
- }
666
- monthCursor = monthCursor.add({ months: this.opts.interval });
667
- }
668
- return this.applyCountLimitAndMergeRDates(dates, iterator);
669
- }
670
- if (this.opts.freq === "WEEKLY" && !(this.opts.byYearDay && this.opts.byYearDay.length > 0)) {
671
- const start = this.originalDtstart;
672
- if (!this.addDtstartIfNeeded(dates, iterator)) {
673
- return this.applyCountLimitAndMergeRDates(dates, iterator);
674
- }
675
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
676
- const tokens = this.opts.byDay ? [...this.opts.byDay] : this.opts.byMonthDay && this.opts.byMonthDay.length > 0 ? Object.keys(dayMap) : [Object.entries(dayMap).find(([, d]) => d === start.dayOfWeek)[0]];
677
- const dows = tokens.map((tok) => dayMap[tok.slice(-2)]).filter((d) => d !== void 0).sort((a, b) => a - b);
678
- const firstWeekDates = dows.map((dw) => {
679
- const delta = (dw - start.dayOfWeek + 7) % 7;
680
- return start.add({ days: delta });
681
- });
682
- let firstOccurrence = firstWeekDates.reduce((a, b) => Temporal.ZonedDateTime.compare(a, b) <= 0 ? a : b);
683
- const wkstDay = (_a = dayMap[this.opts.wkst || "MO"]) != null ? _a : 1;
684
- const firstOccWeekOffset = (firstOccurrence.dayOfWeek - wkstDay + 7) % 7;
685
- let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
686
- while (true) {
687
- if (++iterationCount > this.maxIterations) {
688
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
689
- }
690
- let occs = dows.flatMap((dw) => {
691
- const delta = (dw - wkstDay + 7) % 7;
692
- const sameDate = weekCursor.add({ days: delta });
693
- return this.expandByTime(sameDate);
694
- }).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
695
- occs = this.applyBySetPos(occs);
696
- const { shouldBreak } = this.processOccurrences(
697
- occs,
698
- dates,
699
- start,
700
- iterator,
701
- (occ) => this.matchesByMonth(occ) && this.matchesByMonthDay(occ)
702
- );
703
- if (shouldBreak) {
704
- break;
705
- }
706
- weekCursor = weekCursor.add({ weeks: this.opts.interval });
707
- }
708
- return this.applyCountLimitAndMergeRDates(dates, iterator);
709
- }
710
- if (this.opts.freq === "MONTHLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay) {
711
- const start = this.originalDtstart;
712
- if (!this.addDtstartIfNeeded(dates, iterator)) {
713
- return this.applyCountLimitAndMergeRDates(dates, iterator);
714
- }
715
- const months = [...this.opts.byMonth].sort((a, b) => a - b);
716
- let monthOffset = 0;
717
- let startMonthIndex = months.findIndex((m) => m >= start.month);
718
- if (startMonthIndex === -1) {
719
- startMonthIndex = 0;
720
- monthOffset = 1;
721
- }
722
- while (true) {
723
- if (++iterationCount > this.maxIterations) {
724
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
725
- }
726
- const monthIndex = startMonthIndex + monthOffset;
727
- const targetMonth = months[monthIndex % months.length];
728
- const yearsToAdd = Math.floor(monthIndex / months.length);
729
- const candidate = start.with({
730
- year: start.year + yearsToAdd,
731
- month: targetMonth
732
- });
733
- if (this.opts.until && Temporal.ZonedDateTime.compare(candidate, this.opts.until) > 0) {
734
- break;
735
- }
736
- if (Temporal.ZonedDateTime.compare(candidate, start) >= 0) {
737
- if (iterator && !iterator(candidate, dates.length)) {
738
- break;
739
- }
740
- dates.push(candidate);
741
- if (this.shouldBreakForCountLimit(dates.length)) {
742
- break;
743
- }
744
- }
745
- monthOffset++;
746
- }
747
- return this.applyCountLimitAndMergeRDates(dates, iterator);
748
- }
749
- if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay && !this.opts.byWeekNo) {
750
- const start = this.originalDtstart;
751
- if (!this.addDtstartIfNeeded(dates, iterator)) {
752
- return this.applyCountLimitAndMergeRDates(dates, iterator);
753
- }
754
- const months = [...this.opts.byMonth].sort((a, b) => a - b);
755
- let yearOffset = 0;
756
- while (true) {
757
- if (++iterationCount > this.maxIterations) {
758
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
759
- }
760
- const year = start.year + yearOffset * this.opts.interval;
761
- for (const month of months) {
762
- let occ = start.with({ year, month });
763
- occ = this.applyTimeOverride(occ);
764
- if (Temporal.ZonedDateTime.compare(occ, start) < 0) {
765
- continue;
766
- }
767
- if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
768
- return dates;
769
- }
770
- if (iterator && !iterator(occ, dates.length)) {
771
- return dates;
772
- }
773
- dates.push(occ);
774
- if (this.shouldBreakForCountLimit(dates.length)) {
775
- return this.applyCountLimitAndMergeRDates(dates, iterator);
776
- }
777
- }
778
- yearOffset++;
779
- }
780
- return this.applyCountLimitAndMergeRDates(dates, iterator);
781
- }
782
- 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) {
783
- const start = this.originalDtstart;
784
- if (!this.addDtstartIfNeeded(dates, iterator)) {
785
- return this.applyCountLimitAndMergeRDates(dates, iterator);
786
- }
787
- let yearCursor = start.with({ month: 1, day: 1 });
788
- while (true) {
789
- if (++iterationCount > this.maxIterations) {
790
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
791
- }
792
- const occs = this.generateYearlyOccurrences(yearCursor);
793
- const { shouldBreak } = this.processOccurrences(occs, dates, start, iterator);
794
- if (shouldBreak) {
795
- break;
796
- }
797
- const interval = this.opts.freq === "WEEKLY" ? 1 : this.opts.interval;
798
- yearCursor = yearCursor.add({ years: interval });
799
- if (this.opts.freq === "WEEKLY" && this.opts.until && yearCursor.year > this.opts.until.year) {
800
- break;
801
- }
802
- }
803
- return this.applyCountLimitAndMergeRDates(dates, iterator);
804
- }
805
- if ((this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") && (this.opts.byMonth || this.opts.byWeekNo || this.opts.byYearDay || this.opts.byMonthDay || this.opts.byDay)) {
806
- if (!this.addDtstartIfNeeded(dates, iterator)) {
807
- return this.applyCountLimitAndMergeRDates(dates, iterator);
808
- }
809
- let current = this.computeFirst();
810
- while (true) {
811
- if (++iterationCount > this.maxIterations) {
812
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
813
- }
814
- if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
815
- break;
816
- }
817
- if (this.matchesAll(current)) {
818
- if (iterator && !iterator(current, dates.length)) {
819
- break;
820
- }
821
- dates.push(current);
822
- if (this.shouldBreakForCountLimit(dates.length)) {
823
- break;
824
- }
825
- current = this.nextCandidateSameDate(current);
826
- } else {
827
- current = this.findNextValidDate(current);
828
- }
829
- }
830
- return this.applyCountLimitAndMergeRDates(dates, iterator);
831
- }
832
- if (this.opts.freq === "MONTHLY" && this.opts.byYearDay && this.opts.byYearDay.length > 0 && !this.opts.byDay && !this.opts.byMonthDay) {
833
- const start = this.originalDtstart;
834
- if (!this.addDtstartIfNeeded(dates, iterator)) {
835
- return this.applyCountLimitAndMergeRDates(dates, iterator);
836
- }
837
- let year = start.year;
838
- const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
839
- const interval = this.opts.interval;
840
- const startMonthAbs = start.year * 12 + start.month;
841
- outer_loop: while (true) {
842
- if (this.shouldBreakForCountLimit(dates.length)) {
843
- break;
844
- }
845
- if (++iterationCount > this.maxIterations) {
846
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
847
- }
848
- const yearStart = start.with({ year, month: 1, day: 1 });
849
- const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
850
- for (const yd of yearDays) {
851
- const dayNum = yd > 0 ? yd : lastDayOfYear + yd + 1;
852
- if (dayNum <= 0 || dayNum > lastDayOfYear) continue;
853
- const baseOcc = yearStart.add({ days: dayNum - 1 });
854
- for (const occ of this.expandByTime(baseOcc)) {
855
- if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
856
- if (dates.some((d) => Temporal.ZonedDateTime.compare(d, occ) === 0)) continue;
857
- const occMonthAbs = occ.year * 12 + occ.month;
858
- if ((occMonthAbs - startMonthAbs) % interval !== 0) {
859
- continue;
860
- }
861
- if (!this.matchesByMonth(occ)) {
862
- continue;
863
- }
864
- if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
865
- break outer_loop;
866
- }
867
- if (iterator && !iterator(occ, dates.length)) {
868
- break outer_loop;
869
- }
870
- dates.push(occ);
871
- if (this.shouldBreakForCountLimit(dates.length)) {
872
- break outer_loop;
873
- }
874
- }
875
- }
876
- year++;
877
- if (this.opts.until && year > this.opts.until.year + 2) {
878
- break;
879
- }
880
- if (!this.opts.until && this.opts.count) {
881
- const yearsToScan = Math.ceil(this.opts.count / (this.opts.byYearDay.length || 1)) * interval + 5;
882
- if (year > start.year + yearsToScan) {
883
- break;
884
- }
885
- }
886
- }
887
- return this.applyCountLimitAndMergeRDates(dates, iterator);
888
- }
889
- if ((this.opts.freq === "MINUTELY" || this.opts.freq === "HOURLY" || this.opts.freq === "DAILY") && this.opts.bySetPos) {
890
- const start = this.originalDtstart;
891
- if (!this.addDtstartIfNeeded(dates, iterator)) {
892
- return this.applyCountLimitAndMergeRDates(dates, iterator);
893
- }
894
- let cursor;
895
- let duration;
896
- switch (this.opts.freq) {
897
- case "MINUTELY":
898
- cursor = start.with({ second: 0, microsecond: 0, nanosecond: 0 });
899
- duration = { minutes: this.opts.interval };
900
- break;
901
- case "HOURLY":
902
- cursor = start.with({ minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
903
- duration = { hours: this.opts.interval };
904
- break;
905
- case "DAILY":
906
- cursor = start.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
907
- duration = { days: this.opts.interval };
908
- break;
909
- default:
910
- return this.applyCountLimitAndMergeRDates(dates, iterator);
911
- }
912
- while (true) {
913
- if (++iterationCount > this.maxIterations) {
914
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
915
- }
916
- let periodOccs = this.expandByTime(cursor);
917
- periodOccs = periodOccs.filter((occ) => this.matchesAll(occ));
918
- periodOccs = this.applyBySetPos(periodOccs);
919
- const { shouldBreak } = this.processOccurrences(periodOccs, dates, start, iterator);
920
- if (shouldBreak) {
921
- break;
922
- }
923
- cursor = cursor.add(duration);
924
- if (this.opts.until && Temporal.ZonedDateTime.compare(cursor, this.opts.until) > 0) {
925
- break;
926
- }
927
- }
928
- } else {
929
- let current = this.computeFirst();
930
- if (this.includeDtstart && Temporal.ZonedDateTime.compare(current, this.originalDtstart) > 0) {
931
- if (iterator && !iterator(this.originalDtstart, dates.length)) {
932
- return this.applyCountLimitAndMergeRDates(dates, iterator);
933
- }
934
- dates.push(this.originalDtstart);
935
- if (this.shouldBreakForCountLimit(dates.length)) {
936
- return this.applyCountLimitAndMergeRDates(dates, iterator);
937
- }
938
- }
939
- while (true) {
940
- if (++iterationCount > this.maxIterations) {
941
- throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
942
- }
943
- if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
944
- break;
945
- }
946
- if (this.matchesAll(current)) {
947
- if (iterator && !iterator(current, dates.length)) {
948
- break;
949
- }
950
- dates.push(current);
951
- if (this.shouldBreakForCountLimit(dates.length)) {
952
- break;
953
- }
954
- }
955
- current = this.nextCandidateSameDate(current);
956
- }
957
- }
958
- return this.applyCountLimitAndMergeRDates(dates, iterator);
959
- }
960
- /**
961
- * Converts rDate entries to ZonedDateTime and merges with existing dates.
962
- * @param dates - Array of dates to merge with
963
- * @returns Merged and deduplicated array of dates
964
- */
965
- mergeAndDeduplicateRDates(dates) {
966
- if (!this.opts.rDate) return dates;
967
- dates.push(...this.opts.rDate);
968
- dates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
969
- const dedup = [];
970
- for (const d of dates) {
971
- if (dedup.length === 0 || Temporal.ZonedDateTime.compare(d, dedup[dedup.length - 1]) !== 0) {
972
- dedup.push(d);
973
- }
974
- }
975
- return dedup;
976
- }
977
- /**
978
- * Excludes exDate entries from the given array of dates.
979
- * @param dates - Array of dates to filter
980
- * @returns Filtered array with exDate entries removed
981
- */
982
- excludeExDates(dates) {
983
- if (!this.opts.exDate || this.opts.exDate.length === 0) return dates;
984
- return dates.filter((date) => {
985
- return !this.opts.exDate.some((exDate) => Temporal.ZonedDateTime.compare(date, exDate) === 0);
986
- });
987
- }
988
- /**
989
- * Applies count limit and merges rDates with the rule-generated dates.
990
- * @param dates - Array of dates generated by the rule
991
- * @param iterator - Optional iterator function
992
- * @returns Final array of dates after merging and applying count limit
993
- */
994
- applyCountLimitAndMergeRDates(dates, iterator) {
995
- const merged = this.mergeAndDeduplicateRDates(dates);
996
- const excluded = this.excludeExDates(merged);
997
- if (this.opts.count !== void 0) {
998
- let finalCount = 0;
999
- const finalDates = [];
1000
- for (const d of excluded) {
1001
- if (finalCount >= this.opts.count) break;
1002
- if (iterator && !iterator(d, finalCount)) break;
1003
- finalDates.push(d);
1004
- finalCount++;
1005
- }
1006
- return finalDates;
1007
- }
1008
- return excluded;
1009
- }
1010
- /**
1011
- * Checks if the count limit should break the loop based on rDate presence.
1012
- * @param matchCount - Current number of matches
1013
- * @returns true if the loop should break
1014
- */
1015
- shouldBreakForCountLimit(matchCount) {
1016
- if (this.opts.count === void 0) return false;
1017
- if (!this.opts.rDate) {
1018
- return matchCount >= this.opts.count;
1019
- }
1020
- const rDateCount = this.opts.rDate.length;
1021
- const targetRuleCount = Math.max(this.opts.count - rDateCount, 0);
1022
- const safetyMargin = Math.min(targetRuleCount, 10);
1023
- return matchCount >= targetRuleCount + safetyMargin;
1024
- }
1025
- /**
1026
- * Returns all occurrences of the rule within a specified time window.
1027
- * @param after - The start date or Temporal.ZonedDateTime object.
1028
- * @param before - The end date or Temporal.ZonedDateTime object.
1029
- * @param inc - Optional boolean flag to include the end date in the results.
1030
- * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule within the specified time window.
1031
- */
1032
- between(after, before, inc = false) {
1033
- const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
1034
- const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
1035
- const beforeZdt = Temporal.Instant.from(endInst).toZonedDateTimeISO(this.tzid);
1036
- const tempOpts = __spreadValues({}, this.opts);
1037
- if (!tempOpts.until || Temporal.ZonedDateTime.compare(beforeZdt, tempOpts.until) < 0) {
1038
- tempOpts.until = beforeZdt;
1039
- }
1040
- delete tempOpts.count;
1041
- const tempRule = new _RRuleTemporal(tempOpts);
1042
- const allDates = tempRule.all();
1043
- return allDates.filter((date) => {
1044
- const inst = date.toInstant();
1045
- const afterStart = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
1046
- const beforeEnd = inc ? Temporal.Instant.compare(inst, endInst) <= 0 : Temporal.Instant.compare(inst, endInst) < 0;
1047
- return afterStart && beforeEnd;
1048
- });
1049
- }
1050
- /**
1051
- * Returns the next occurrence of the rule after a specified date.
1052
- * @param after - The start date or Temporal.ZonedDateTime object.
1053
- * @param inc - Optional boolean flag to include occurrences on the start date.
1054
- * @returns The next occurrence of the rule after the specified date or null if no occurrences are found.
1055
- */
1056
- next(after = /* @__PURE__ */ new Date(), inc = false) {
1057
- const afterInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
1058
- let result = null;
1059
- this.all((occ) => {
1060
- const inst = occ.toInstant();
1061
- const ok = inc ? Temporal.Instant.compare(inst, afterInst) >= 0 : Temporal.Instant.compare(inst, afterInst) > 0;
1062
- if (ok) {
1063
- result = occ;
1064
- return false;
1065
- }
1066
- return true;
1067
- });
1068
- return result;
1069
- }
1070
- /**
1071
- * Returns the previous occurrence of the rule before a specified date.
1072
- * @param before - The end date or Temporal.ZonedDateTime object.
1073
- * @param inc - Optional boolean flag to include occurrences on the end date.
1074
- * @returns The previous occurrence of the rule before the specified date or null if no occurrences are found.
1075
- */
1076
- previous(before = /* @__PURE__ */ new Date(), inc = false) {
1077
- const beforeInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
1078
- let prev = null;
1079
- this.all((occ) => {
1080
- const inst = occ.toInstant();
1081
- const beyond = inc ? Temporal.Instant.compare(inst, beforeInst) > 0 : Temporal.Instant.compare(inst, beforeInst) >= 0;
1082
- if (beyond) return false;
1083
- prev = occ;
1084
- return true;
1085
- });
1086
- return prev;
1087
- }
1088
- toString() {
1089
- const iso = this.originalDtstart.toString({ smallestUnit: "second" }).replace(/[-:]/g, "");
1090
- const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
1091
- const rule = [];
1092
- const {
1093
- freq,
1094
- interval,
1095
- count,
1096
- until,
1097
- byHour,
1098
- byMinute,
1099
- bySecond,
1100
- byDay,
1101
- byMonth,
1102
- byMonthDay,
1103
- bySetPos,
1104
- byWeekNo,
1105
- byYearDay,
1106
- wkst,
1107
- rDate,
1108
- exDate
1109
- } = this.opts;
1110
- rule.push(`FREQ=${freq}`);
1111
- if (interval !== 1) rule.push(`INTERVAL=${interval}`);
1112
- if (count !== void 0) rule.push(`COUNT=${count}`);
1113
- if (until) {
1114
- rule.push(`UNTIL=${this.formatIcsDateTime(until)}`);
1115
- }
1116
- if (byHour) rule.push(`BYHOUR=${byHour.join(",")}`);
1117
- if (byMinute) rule.push(`BYMINUTE=${byMinute.join(",")}`);
1118
- if (bySecond) rule.push(`BYSECOND=${bySecond.join(",")}`);
1119
- if (byDay) rule.push(`BYDAY=${byDay.join(",")}`);
1120
- if (byMonth) rule.push(`BYMONTH=${byMonth.join(",")}`);
1121
- if (byMonthDay) rule.push(`BYMONTHDAY=${byMonthDay.join(",")}`);
1122
- if (bySetPos) rule.push(`BYSETPOS=${bySetPos.join(",")}`);
1123
- if (byWeekNo) rule.push(`BYWEEKNO=${byWeekNo.join(",")}`);
1124
- if (byYearDay) rule.push(`BYYEARDAY=${byYearDay.join(",")}`);
1125
- if (wkst) rule.push(`WKST=${wkst}`);
1126
- const lines = [dtLine, `RRULE:${rule.join(";")}`];
1127
- if (rDate) {
1128
- lines.push(`RDATE:${this.joinDates(rDate)}`);
1129
- }
1130
- if (exDate) {
1131
- lines.push(`EXDATE:${this.joinDates(exDate)}`);
1132
- }
1133
- return lines.join("\n");
1134
- }
1135
- formatIcsDateTime(date) {
1136
- return date.toInstant().toString().replace(/[-:]/g, "").slice(0, 15) + "Z";
1137
- }
1138
- joinDates(dates) {
1139
- return dates.map((d) => this.formatIcsDateTime(d));
1140
- }
1141
- /**
1142
- * Given any date in a month, return all the ZonedDateTimes in that month
1143
- * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
1144
- */
1145
- generateMonthlyOccurrences(sample) {
1146
- var _a;
1147
- const { byDay, byMonth, byMonthDay } = this.opts;
1148
- if (byMonth && !byMonth.includes(sample.month)) return [];
1149
- const lastDay = sample.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
1150
- let byMonthDayHits = [];
1151
- if (byMonthDay && byMonthDay.length > 0) {
1152
- byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
1153
- }
1154
- if (!byDay && byMonthDay && byMonthDay.length > 0) {
1155
- if (byMonthDayHits.length === 0) {
1156
- return [];
1157
- }
1158
- const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
1159
- return dates.flatMap((z) => this.expandByTime(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1160
- }
1161
- if (!byDay) {
1162
- return this.expandByTime(sample);
1163
- }
1164
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1165
- const tokens = byDay.map((tok) => {
1166
- const m = tok.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
1167
- if (!m) return null;
1168
- return { ord: m[1] ? parseInt(m[1], 10) : 0, wd: dayMap[m[2]] };
1169
- }).filter((x) => x !== null);
1170
- const buckets = {};
1171
- let cursor = sample.with({ day: 1 });
1172
- while (cursor.month === sample.month) {
1173
- const dow = cursor.dayOfWeek;
1174
- (buckets[dow] || (buckets[dow] = [])).push(cursor.day);
1175
- cursor = cursor.add({ days: 1 });
1176
- }
1177
- const byDayHits = [];
1178
- for (const { ord, wd } of tokens) {
1179
- const list = (_a = buckets[wd]) != null ? _a : [];
1180
- if (!list.length) continue;
1181
- if (ord === 0) {
1182
- for (const d of list) byDayHits.push(d);
1183
- } else {
1184
- const idx = ord > 0 ? ord - 1 : list.length + ord;
1185
- const dayN = list[idx];
1186
- if (dayN) byDayHits.push(dayN);
1187
- }
1188
- }
1189
- let finalDays = byDayHits;
1190
- if (byMonthDay && byMonthDay.length > 0) {
1191
- if (byMonthDayHits.length === 0) {
1192
- return [];
1193
- }
1194
- finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
1195
- }
1196
- const hits = finalDays.map((d) => sample.with({ day: d }));
1197
- return hits.flatMap((z) => this.expandByTime(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1198
- }
1199
- /**
1200
- * Given any date in a year, return all ZonedDateTimes in that year matching
1201
- * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
1202
- * if BYMONTH is not specified.
1203
- */
1204
- generateYearlyOccurrences(sample) {
1205
- var _a;
1206
- const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : this.opts.byMonthDay ? [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] : [this.originalDtstart.month];
1207
- let occs = [];
1208
- const hasOrdinalByDay = this.opts.byDay && this.opts.byDay.some((t) => /^[+-]?\d/.test(t));
1209
- if (hasOrdinalByDay && !this.opts.byMonth) {
1210
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1211
- for (const tok of this.opts.byDay) {
1212
- const m = tok.match(/^([+-]?\d{1,2})(MO|TU|WE|TH|FR|SA|SU)$/);
1213
- if (!m) continue;
1214
- const ord = parseInt(m[1], 10);
1215
- const wd = dayMap[m[2]];
1216
- let dt;
1217
- if (ord > 0) {
1218
- const jan1 = sample.with({ month: 1, day: 1 });
1219
- const delta = (wd - jan1.dayOfWeek + 7) % 7;
1220
- dt = jan1.add({ days: delta + 7 * (ord - 1) });
1221
- } else {
1222
- const dec31 = sample.with({ month: 12, day: 31 });
1223
- const delta = (dec31.dayOfWeek - wd + 7) % 7;
1224
- dt = dec31.subtract({ days: delta + 7 * (-ord - 1) });
1225
- }
1226
- occs.push(...this.expandByTime(dt));
1227
- }
1228
- } else if (!this.opts.byYearDay && !this.opts.byWeekNo) {
1229
- occs = months.flatMap((m) => {
1230
- const monthSample = sample.with({ month: m, day: 1 });
1231
- return this.generateMonthlyOccurrences(monthSample);
1232
- });
1233
- }
1234
- if (this.opts.byYearDay) {
1235
- const last = sample.with({ month: 12, day: 31 }).dayOfYear;
1236
- for (const d of this.opts.byYearDay) {
1237
- const dayNum = d > 0 ? d : last + d + 1;
1238
- 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 });
1239
- if (!this.opts.byMonth || this.opts.byMonth.includes(dt.month)) {
1240
- occs.push(...this.expandByTime(dt));
1241
- }
1242
- }
1243
- }
1244
- if (this.opts.byWeekNo) {
1245
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1246
- const wkst = dayMap[this.opts.wkst || "MO"];
1247
- const jan1 = sample.with({ month: 1, day: 1 });
1248
- const delta = (jan1.dayOfWeek - wkst + 7) % 7;
1249
- const firstWeekStart = jan1.subtract({ days: delta });
1250
- const isLeapYear = jan1.inLeapYear;
1251
- const lastWeek = jan1.dayOfWeek === 4 || isLeapYear && jan1.dayOfWeek === 3 ? 53 : 52;
1252
- const tokens = ((_a = this.opts.byDay) == null ? void 0 : _a.length) ? this.opts.byDay.map((tok) => {
1253
- var _a2;
1254
- return (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
1255
- }) : [Object.entries(dayMap).find(([, d]) => d === this.originalDtstart.dayOfWeek)[0]];
1256
- for (const weekNo of this.opts.byWeekNo) {
1257
- const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
1258
- const weekStart = firstWeekStart.add({ weeks: weekIndex });
1259
- for (const tok of tokens) {
1260
- if (!tok) continue;
1261
- const targetDow = dayMap[tok];
1262
- const inst = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
1263
- if (!this.opts.byMonth || this.opts.byMonth.includes(inst.month)) {
1264
- occs.push(...this.expandByTime(inst));
1265
- }
1266
- }
1267
- }
1268
- }
1269
- occs = occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1270
- occs = this.applyBySetPos(occs);
1271
- return occs;
1272
- }
1273
- /**
1274
- * Helper to find the next valid value from a sorted array
1275
- */
1276
- findNextValidValue(currentValue, validValues, compare) {
1277
- return validValues.find((v) => compare(v, currentValue) > 0) || null;
1278
- }
1279
- /**
1280
- * Efficiently find the next valid date for MINUTELY and SECONDLY frequency by jumping over
1281
- * large gaps when BYXXX constraints don't match.
1282
- */
1283
- findNextValidDate(current) {
1284
- if (this.opts.byMonth && !this.opts.byMonth.includes(current.month)) {
1285
- const months = [...this.opts.byMonth].sort((a, b) => a - b);
1286
- const nextMonth = this.findNextValidValue(current.month, months, (a, b) => a - b);
1287
- if (nextMonth) {
1288
- current = current.with({ month: nextMonth, day: 1, hour: 0, minute: 0, second: 0 });
1289
- } else {
1290
- current = current.add({ years: 1 }).with({ month: months[0], day: 1, hour: 0, minute: 0, second: 0 });
1291
- }
1292
- current = this.applyTimeOverride(current);
1293
- return current;
1294
- }
1295
- if (this.opts.byYearDay && !this.matchesByYearDay(current)) {
1296
- const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
1297
- const currentYearDay = current.dayOfYear;
1298
- const lastDayOfYear = current.with({ month: 12, day: 31 }).dayOfYear;
1299
- let nextYearDay = yearDays.find((d) => {
1300
- const dayNum = d > 0 ? d : lastDayOfYear + d + 1;
1301
- return dayNum > currentYearDay;
1302
- });
1303
- if (nextYearDay) {
1304
- const dayNum = nextYearDay > 0 ? nextYearDay : lastDayOfYear + nextYearDay + 1;
1305
- if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
1306
- current = current.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
1307
- } else {
1308
- current = current.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1309
- }
1310
- } else {
1311
- const nextYear = current.add({ years: 1 });
1312
- const nextYearLastDay = nextYear.with({ month: 12, day: 31 }).dayOfYear;
1313
- const firstYearDay = yearDays[0];
1314
- if (firstYearDay !== void 0) {
1315
- const dayNum = firstYearDay > 0 ? firstYearDay : nextYearLastDay + firstYearDay + 1;
1316
- if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
1317
- current = nextYear.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
1318
- } else {
1319
- current = nextYear.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1320
- }
1321
- }
1322
- }
1323
- current = this.applyTimeOverride(current);
1324
- return current;
1325
- }
1326
- if (this.opts.byWeekNo && !this.matchesByWeekNo(current)) {
1327
- current = current.add({ weeks: 1 }).with({ hour: 0, minute: 0, second: 0 });
1328
- current = this.applyTimeOverride(current);
1329
- return current;
1330
- }
1331
- if (this.opts.byMonthDay && !this.matchesByMonthDay(current)) {
1332
- const monthDays = [...this.opts.byMonthDay].sort((a, b) => a - b);
1333
- const lastDayOfMonth = current.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
1334
- const currentDay = current.day;
1335
- const validDays = monthDays.map((d) => d > 0 ? d : lastDayOfMonth + d + 1).filter((d) => d > 0 && d <= lastDayOfMonth).sort((a, b) => a - b);
1336
- const nextDay = this.findNextValidValue(currentDay, validDays, (a, b) => a - b);
1337
- if (nextDay) {
1338
- current = current.with({ day: nextDay, hour: 0, minute: 0, second: 0 });
1339
- } else {
1340
- const nextMonth = current.add({ months: 1 }).with({ day: 1 });
1341
- const nextMonthLastDay = nextMonth.add({ months: 1 }).subtract({ days: 1 }).day;
1342
- const firstMonthDay = monthDays[0];
1343
- if (firstMonthDay !== void 0) {
1344
- const dayNum = firstMonthDay > 0 ? firstMonthDay : nextMonthLastDay + firstMonthDay + 1;
1345
- current = nextMonth.with({
1346
- day: Math.max(1, Math.min(dayNum, nextMonthLastDay)),
1347
- hour: 0,
1348
- minute: 0,
1349
- second: 0
1350
- });
1351
- }
1352
- }
1353
- current = this.applyTimeOverride(current);
1354
- return current;
1355
- }
1356
- if (this.opts.byDay && !this.matchesByDay(current)) {
1357
- const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1358
- const currentDow = current.dayOfWeek;
1359
- let nextDow = 8;
1360
- for (const token of this.opts.byDay) {
1361
- const match = token.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
1362
- if (match && !match[1]) {
1363
- const dow = dayMap[match[2]];
1364
- if (dow && dow > currentDow) {
1365
- nextDow = Math.min(nextDow, dow);
1366
- }
1367
- }
1368
- }
1369
- if (nextDow <= 7) {
1370
- current = current.add({ days: nextDow - currentDow }).with({ hour: 0, minute: 0, second: 0 });
1371
- } else {
1372
- current = current.add({ days: 7 - currentDow + 1 }).with({ hour: 0, minute: 0, second: 0 });
1373
- }
1374
- current = this.applyTimeOverride(current);
1375
- return current;
1376
- }
1377
- return this.nextCandidateSameDate(current);
1378
- }
1379
- applyBySetPos(list) {
1380
- const { bySetPos } = this.opts;
1381
- if (!bySetPos || !bySetPos.length) return list;
1382
- const sorted = [...list].sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1383
- const out = [];
1384
- const len = sorted.length;
1385
- for (const pos of bySetPos) {
1386
- const idx = pos > 0 ? pos - 1 : len + pos;
1387
- if (idx >= 0 && idx < len) out.push(sorted[idx]);
1388
- }
1389
- return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1390
- }
1391
- };
1392
-
1393
- export {
1394
- RRuleTemporal
1395
- };