rrule-temporal 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ggaabe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # rrule-temporal
2
+
3
+ Recurrence rule (RFC 5545) processing using Temporal PlainDate/PlainDateTime.
4
+
5
+ This was created to advance the rrule library to use Temporal, and to provide a more modern API, as the original rrule library is [not maintained anymore](https://github.com/jkbrzt/rrule/issues/615). Maintainers suggested to use Temporal instead of Date:
6
+
7
+ https://github.com/jkbrzt/rrule/issues/450#issuecomment-1055853095
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install rrule-temporal
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ // TODO: Add usage examples
19
+ ```
@@ -0,0 +1,35 @@
1
+ import { Temporal } from "@js-temporal/polyfill";
2
+ type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
3
+ interface BaseOpts {
4
+ tzid?: string;
5
+ }
6
+ interface ManualOpts extends BaseOpts {
7
+ freq: Freq;
8
+ interval?: number;
9
+ count?: number;
10
+ until?: Temporal.ZonedDateTime;
11
+ byHour?: number[];
12
+ byMinute?: number[];
13
+ dtstart: string | Temporal.ZonedDateTime;
14
+ }
15
+ interface IcsOpts extends BaseOpts {
16
+ rruleString: string;
17
+ }
18
+ export type RRuleOpts = ManualOpts | IcsOpts;
19
+ export declare class RRuleTemporal {
20
+ private tzid;
21
+ private originalDtstart;
22
+ private opts;
23
+ constructor(params: {
24
+ rruleString: string;
25
+ } | ManualOpts);
26
+ private rawAdvance;
27
+ private applyTimeOverride;
28
+ private computeFirst;
29
+ all(iterator?: (date: Temporal.ZonedDateTime, i: number) => boolean): Temporal.ZonedDateTime[];
30
+ between(after: Date | Temporal.ZonedDateTime, before: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime[];
31
+ next(after?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
32
+ previous(before?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
33
+ toString(): string;
34
+ }
35
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,256 @@
1
+ // rrule-temporal.ts
2
+ // A robust RFC-5545 RRule implementation using the Temporal polyfill
3
+ // Supports FREQ=DAILY|WEEKLY|MONTHLY|YEARLY, BYHOUR, BYMINUTE, DTSTART, UNTIL, COUNT, TZID
4
+ import { Temporal } from "@js-temporal/polyfill";
5
+ /**
6
+ * Parse either a full ICS snippet or an RRULE line into ManualOpts
7
+ * Accepts:
8
+ * - "DTSTART...\nRRULE:..." ICS snippet
9
+ * - "RRULE:..." alone (dtstart must be provided by caller)
10
+ */
11
+ function parseRRuleString(input, fallbackDtstart) {
12
+ let dtstart;
13
+ let tzid = "";
14
+ let rruleLine;
15
+ console.log("input", input);
16
+ if (/^DTSTART/m.test(input)) {
17
+ // ICS snippet: split DTSTART and RRULE
18
+ const [dtLine, rrLine] = input.split(/\r?\n/);
19
+ const m = dtLine?.match(/DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{6})/);
20
+ if (!m)
21
+ throw new Error("Invalid DTSTART in ICS snippet");
22
+ tzid = m[1] || tzid;
23
+ const isoDate = `${m[2].slice(0, 4)}-${m[2].slice(4, 6)}-${m[2].slice(6, 8)}T${m[2].slice(9)}`;
24
+ dtstart = Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid);
25
+ rruleLine = rrLine;
26
+ }
27
+ else {
28
+ // Only RRULE line; require fallback
29
+ if (!fallbackDtstart)
30
+ throw new Error("dtstart required when parsing RRULE alone");
31
+ dtstart = fallbackDtstart;
32
+ tzid = fallbackDtstart.timeZoneId;
33
+ rruleLine = input.replace(/^RRULE:/, "RRULE:");
34
+ }
35
+ // Parse RRULE
36
+ const parts = rruleLine.replace(/^RRULE:/, "").split(";");
37
+ const opts = { dtstart, tzid, freq: "DAILY" };
38
+ for (const part of parts) {
39
+ const [key, val] = part.split("=");
40
+ switch (key) {
41
+ case "FREQ":
42
+ opts.freq = val;
43
+ break;
44
+ case "INTERVAL":
45
+ opts.interval = parseInt(val, 10);
46
+ break;
47
+ case "COUNT":
48
+ opts.count = parseInt(val, 10);
49
+ break;
50
+ case "UNTIL": {
51
+ // RFC5545 UNTIL is YYYYMMDDTHHMMSSZ or without Z
52
+ if (/Z$/.test(val)) {
53
+ const iso = `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6, 8)}T${val.slice(9, 15)}Z`;
54
+ opts.until = Temporal.Instant.from(iso).toZonedDateTimeISO(tzid || "UTC");
55
+ }
56
+ else {
57
+ const iso = `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6, 8)}T${val.slice(9, 15)}`;
58
+ opts.until = Temporal.PlainDateTime.from(iso).toZonedDateTime(tzid || "UTC");
59
+ }
60
+ break;
61
+ }
62
+ case "BYHOUR":
63
+ opts.byHour = val.split(",").map((n) => parseInt(n, 10));
64
+ break;
65
+ case "BYMINUTE":
66
+ opts.byMinute = val.split(",").map((n) => parseInt(n, 10));
67
+ break;
68
+ }
69
+ }
70
+ return opts;
71
+ }
72
+ export class RRuleTemporal {
73
+ tzid;
74
+ originalDtstart;
75
+ opts;
76
+ constructor(params) {
77
+ let manual;
78
+ if ("rruleString" in params) {
79
+ // parse full ICS snippet
80
+ manual = parseRRuleString(params.rruleString);
81
+ this.tzid = manual.tzid || "UTC";
82
+ this.originalDtstart = manual.dtstart;
83
+ }
84
+ else {
85
+ // manual options
86
+ manual = { ...params };
87
+ if (typeof manual.dtstart === "string") {
88
+ throw new Error("Manual dtstart must be a ZonedDateTime");
89
+ }
90
+ manual.tzid = manual.tzid || manual.dtstart.timeZoneId;
91
+ this.tzid = manual.tzid;
92
+ this.originalDtstart = manual.dtstart;
93
+ }
94
+ if (!manual.freq)
95
+ throw new Error("RRULE must include FREQ");
96
+ // default interval
97
+ manual.interval = manual.interval ?? 1;
98
+ this.opts = manual;
99
+ }
100
+ rawAdvance(zdt) {
101
+ const { freq, interval } = this.opts;
102
+ switch (freq) {
103
+ case "DAILY":
104
+ return zdt.add({ days: interval });
105
+ case "WEEKLY":
106
+ return zdt.add({ weeks: interval });
107
+ case "MONTHLY":
108
+ return zdt.add({ months: interval });
109
+ case "YEARLY":
110
+ return zdt.add({ years: interval });
111
+ case "HOURLY":
112
+ return zdt.add({ hours: interval });
113
+ case "MINUTELY":
114
+ return zdt.add({ minutes: interval });
115
+ case "SECONDLY":
116
+ return zdt.add({ seconds: interval });
117
+ default:
118
+ throw new Error(`Unsupported FREQ: ${freq}`);
119
+ }
120
+ }
121
+ applyTimeOverride(zdt) {
122
+ const { byHour, byMinute } = this.opts;
123
+ let dt = zdt;
124
+ if (byHour)
125
+ dt = dt.with({ hour: byHour[0] });
126
+ if (byMinute)
127
+ dt = dt.with({ minute: byMinute[0] });
128
+ return dt;
129
+ }
130
+ computeFirst() {
131
+ const { byHour, byMinute } = this.opts;
132
+ let candidate = this.originalDtstart;
133
+ if (byHour || byMinute) {
134
+ candidate = this.applyTimeOverride(candidate);
135
+ if (Temporal.Instant.compare(candidate.toInstant(), this.originalDtstart.toInstant()) < 0) {
136
+ candidate = this.applyTimeOverride(this.rawAdvance(this.originalDtstart));
137
+ }
138
+ }
139
+ return candidate;
140
+ }
141
+ all(iterator) {
142
+ if (!this.opts.count && !this.opts.until && !iterator) {
143
+ throw new Error("all() requires iterator when no COUNT/UNTIL");
144
+ }
145
+ const dates = [];
146
+ let current = this.computeFirst();
147
+ let i = 0;
148
+ while (true) {
149
+ if (this.opts.until &&
150
+ Temporal.ZonedDateTime.compare(current, this.opts.until) > 0)
151
+ break;
152
+ if (this.opts.count !== undefined && i >= this.opts.count)
153
+ break;
154
+ if (iterator && !iterator(current, i))
155
+ break;
156
+ dates.push(current);
157
+ const base = this.rawAdvance(current);
158
+ current = this.applyTimeOverride(base);
159
+ i++;
160
+ }
161
+ return dates;
162
+ }
163
+ between(after, before, inc = false) {
164
+ const startInst = after instanceof Date
165
+ ? Temporal.Instant.from(after.toISOString())
166
+ : after.toInstant();
167
+ const endInst = before instanceof Date
168
+ ? Temporal.Instant.from(before.toISOString())
169
+ : before.toInstant();
170
+ const results = [];
171
+ let current = this.computeFirst();
172
+ while (true) {
173
+ const inst = current.toInstant();
174
+ // NEW: we break *earlier* when exclusive
175
+ if (inc) {
176
+ // inclusive: keep inst ≤ endInst, so only break when inst > endInst
177
+ if (Temporal.Instant.compare(inst, endInst) > 0)
178
+ break;
179
+ }
180
+ else {
181
+ // exclusive: drop inst ≥ endInst, so break when inst ≥ endInst
182
+ if (Temporal.Instant.compare(inst, endInst) >= 0)
183
+ break;
184
+ }
185
+ // push any inst ≥ startInst
186
+ if (Temporal.Instant.compare(inst, startInst) >= 0) {
187
+ results.push(current);
188
+ }
189
+ current = this.applyTimeOverride(this.rawAdvance(current));
190
+ }
191
+ return results;
192
+ }
193
+ next(after = new Date(), inc = false) {
194
+ const afterInst = after instanceof Date
195
+ ? Temporal.Instant.from(after.toISOString())
196
+ : after.toInstant();
197
+ let current = this.computeFirst();
198
+ let i = 0;
199
+ while (true) {
200
+ const inst = current.toInstant();
201
+ if (inc
202
+ ? Temporal.Instant.compare(inst, afterInst) >= 0
203
+ : Temporal.Instant.compare(inst, afterInst) > 0)
204
+ return current;
205
+ if (this.opts.count !== undefined && i >= this.opts.count - 1)
206
+ return null;
207
+ if (this.opts.until &&
208
+ Temporal.ZonedDateTime.compare(current, this.opts.until) >= 0)
209
+ return null;
210
+ current = this.applyTimeOverride(this.rawAdvance(current));
211
+ i++;
212
+ }
213
+ }
214
+ previous(before = new Date(), inc = false) {
215
+ const beforeInst = before instanceof Date
216
+ ? Temporal.Instant.from(before.toISOString())
217
+ : before.toInstant();
218
+ let current = this.computeFirst();
219
+ let prev = null;
220
+ let i = 0;
221
+ while (true) {
222
+ const inst = current.toInstant();
223
+ if (inc
224
+ ? Temporal.Instant.compare(inst, beforeInst) > 0
225
+ : Temporal.Instant.compare(inst, beforeInst) >= 0)
226
+ break;
227
+ prev = current;
228
+ if (this.opts.count !== undefined && i >= this.opts.count - 1)
229
+ break;
230
+ if (this.opts.until &&
231
+ Temporal.ZonedDateTime.compare(current, this.opts.until) >= 0)
232
+ break;
233
+ current = this.applyTimeOverride(this.rawAdvance(current));
234
+ i++;
235
+ }
236
+ return prev;
237
+ }
238
+ toString() {
239
+ const iso = this.originalDtstart
240
+ .toString({ smallestUnit: "second" })
241
+ .replace(/[-:]/g, "");
242
+ const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
243
+ const parts = [];
244
+ const { freq, interval, count, byHour, byMinute } = this.opts;
245
+ parts.push(`FREQ=${freq}`);
246
+ if (interval !== 1)
247
+ parts.push(`INTERVAL=${interval}`);
248
+ if (count !== undefined)
249
+ parts.push(`COUNT=${count}`);
250
+ if (byHour)
251
+ parts.push(`BYHOUR=${byHour.join(",")}`);
252
+ if (byMinute)
253
+ parts.push(`BYMINUTE=${byMinute.join(",")}`);
254
+ return [dtLine, `RRULE:${parts.join(";")}`].join("\n");
255
+ }
256
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,135 @@
1
+ import { RRuleTemporal } from "../index";
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+ describe("RRuleTemporal - ICS snippet parsing", () => {
4
+ const ics = `DTSTART;TZID=America/Chicago:20250320T170000
5
+ RRULE:FREQ=DAILY;BYHOUR=17;BYMINUTE=0;COUNT=5`.trim();
6
+ const rule = new RRuleTemporal({ rruleString: ics });
7
+ test("toString reproduces original ICS (excluding COUNT position)", () => {
8
+ const out = rule.toString();
9
+ expect(out).toContain("DTSTART;TZID=America/Chicago:20250320T170000");
10
+ expect(out).toContain("FREQ=DAILY");
11
+ expect(out).toContain("BYHOUR=17");
12
+ expect(out).toContain("BYMINUTE=0");
13
+ expect(out).toContain("COUNT=5");
14
+ });
15
+ test("all() returns exactly count occurrences at 5pm CT each day", () => {
16
+ const dates = rule.all();
17
+ expect(dates).toHaveLength(5);
18
+ for (let i = 0; i < dates.length; i++) {
19
+ const dt = dates[i];
20
+ if (!dt) {
21
+ throw new Error("dt is undefined");
22
+ }
23
+ // 17:00 CT should be 22:00 UTC during CDT
24
+ expect(dt.hour).toBe(17);
25
+ expect(dt.minute).toBe(0);
26
+ // consecutive days
27
+ const next = dates[i + 1];
28
+ if (next) {
29
+ const diff = Temporal.Duration.compare(next.since(dt), Temporal.Duration.from({ days: 1 }));
30
+ expect(diff).toBe(0);
31
+ }
32
+ }
33
+ });
34
+ });
35
+ describe("RRuleTemporal - Manual options", () => {
36
+ const dtstart = Temporal.ZonedDateTime.from({
37
+ year: 2025,
38
+ month: 4,
39
+ day: 20,
40
+ hour: 8,
41
+ minute: 30,
42
+ timeZone: "America/Chicago",
43
+ });
44
+ const rule = new RRuleTemporal({
45
+ freq: "DAILY",
46
+ interval: 2,
47
+ count: 3,
48
+ byHour: [9],
49
+ byMinute: [15],
50
+ dtstart,
51
+ tzid: "America/Chicago",
52
+ });
53
+ test("all() respects manual interval and overrides time", () => {
54
+ const dates = rule.all();
55
+ expect(dates).toHaveLength(3);
56
+ dates.forEach((d, idx) => {
57
+ expect(d.hour).toBe(9);
58
+ expect(d.minute).toBe(15);
59
+ if (idx > 0) {
60
+ const prev = dates[idx - 1];
61
+ if (!prev) {
62
+ throw new Error("prev is undefined");
63
+ }
64
+ const diffDays = Math.round(d.since(prev).total({ unit: "days" }));
65
+ expect(diffDays).toBe(2);
66
+ }
67
+ });
68
+ });
69
+ });
70
+ describe("RRuleTemporal - between()", () => {
71
+ const ics = `DTSTART;TZID=America/Chicago:20250401T000000
72
+ RRULE:FREQ=DAILY;BYHOUR=0;BYMINUTE=0;UNTIL=20250405T000000Z`.trim();
73
+ const rule = new RRuleTemporal({ rruleString: ics });
74
+ const start = new Date(Date.UTC(2025, 3, 2, 0, 0)); // Apr 2 00:00 UTC
75
+ // after:
76
+ const end = new Date(
77
+ // 2025-04-04 00:00 America/Chicago → 05:00 UTC
78
+ Date.UTC(2025, 3, 4, 5, 0, 0));
79
+ test("between returns occurrences in window inclusive/exclusive", () => {
80
+ const arrExc = rule.between(start, end, false);
81
+ expect(arrExc.map((d) => d.day)).toEqual([2, 3]);
82
+ const arrInc = rule.between(start, end, true);
83
+ expect(arrInc.map((d) => d.day)).toEqual([2, 3, 4]);
84
+ });
85
+ });
86
+ describe("RRuleTemporal - next() and previous()", () => {
87
+ const ics = `DTSTART;TZID=UTC:20250101T120000
88
+ RRULE:FREQ=MONTHLY;BYHOUR=12;BYMINUTE=0;COUNT=12`.trim();
89
+ const rule = new RRuleTemporal({ rruleString: ics });
90
+ test("next gives first upcoming after a date", () => {
91
+ const after = new Date(Temporal.ZonedDateTime.from({
92
+ year: 2025,
93
+ month: 3,
94
+ day: 15,
95
+ hour: 0,
96
+ minute: 0,
97
+ timeZone: "UTC",
98
+ }).toInstant().epochMilliseconds);
99
+ const nxt = rule.next(after);
100
+ expect(nxt).not.toBeNull();
101
+ if (!nxt) {
102
+ throw new Error("nxt is undefined");
103
+ }
104
+ expect(nxt.month).toBe(4); // April’s occurrence
105
+ expect(nxt.hour).toBe(12);
106
+ });
107
+ test("previous gives last before a date", () => {
108
+ const before = new Date(Temporal.ZonedDateTime.from({
109
+ year: 2025,
110
+ month: 6,
111
+ day: 5,
112
+ hour: 0,
113
+ minute: 0,
114
+ timeZone: "UTC",
115
+ }).toInstant().epochMilliseconds);
116
+ const prev = rule.previous(before);
117
+ expect(prev).not.toBeNull();
118
+ if (!prev) {
119
+ throw new Error("prev is undefined");
120
+ }
121
+ expect(prev.month).toBe(6); // June’s occurrence (on or before)
122
+ });
123
+ });
124
+ describe("RRuleTemporal - unbounded all() error", () => {
125
+ const ics = `DTSTART;TZID=UTC:20250101T000000
126
+ RRULE:FREQ=DAILY`.trim();
127
+ const rule = new RRuleTemporal({ rruleString: ics });
128
+ test("all() throws without iterator on unbounded", () => {
129
+ expect(() => rule.all()).toThrow(/requires iterator/);
130
+ });
131
+ test("all() works with iterator limit", () => {
132
+ const dates = rule.all((dt, i) => i < 3);
133
+ expect(dates).toHaveLength(3);
134
+ });
135
+ });
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "rrule-temporal",
3
+ "version": "0.1.0",
4
+ "description": "Recurrence rule processing using Temporal PlainDate/PlainDateTime",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "type": "module",
9
+ "scripts": {
10
+ "build": "tsc --build",
11
+ "test": "jest"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/ggaabe/rrule-temporal.git"
16
+ },
17
+ "keywords": [
18
+ "rrule",
19
+ "recurrence",
20
+ "temporal",
21
+ "date",
22
+ "time",
23
+ "plaindate",
24
+ "plaindatetime"
25
+ ],
26
+ "author": "ggaabe",
27
+ "license": "MIT",
28
+ "bugs": {
29
+ "url": "https://github.com/ggaabe/rrule-temporal/issues"
30
+ },
31
+ "homepage": "https://github.com/ggaabe/rrule-temporal#readme",
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "devDependencies": {
36
+ "@types/jest": "^29.5.14",
37
+ "@types/node": "^22.14.1",
38
+ "jest": "^29.7.0",
39
+ "ts-jest": "^29.3.2",
40
+ "ts-node": "^10.9.2",
41
+ "typescript": "^5.8.3"
42
+ },
43
+ "dependencies": {
44
+ "@js-temporal/polyfill": "^0.5.1"
45
+ }
46
+ }