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