neramjs 0.0.0-stage → 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.
@@ -0,0 +1,731 @@
1
+ import { civilFromDays, dayOfYear, daysInMonth, daysInYear, weekOfYear, weeksInYear } from '../calendar.js';
2
+ import { formatList } from '../intl.js';
3
+ import { localeData, ordinal } from '../locale.js';
4
+ import { Neram, neram } from '../neram.js';
5
+ import { normalizeZone, utcFromParts, wallOfMs, wallToEpoch } from '../zone.js';
6
+ import { Schedule } from './schedule.js';
7
+ // ---------------------------------------------------------------------------
8
+ // Internals
9
+ // ---------------------------------------------------------------------------
10
+ const FREQS = ['yearly', 'monthly', 'weekly', 'daily', 'hourly', 'minutely', 'secondly'];
11
+ const OPTION_KEYS = new Set([
12
+ 'freq', 'dtstart', 'tz', 'allDay', 'interval', 'count', 'until', 'wkst', 'byMonth', 'byWeekNo', 'byYearDay',
13
+ 'byMonthDay', 'byDay', 'byHour', 'byMinute', 'bySecond', 'bySetPos', 'rdate', 'exdate',
14
+ ]);
15
+ const YEARLY = 0, MONTHLY = 1, WEEKLY = 2, DAILY = 3, HOURLY = 4, MINUTELY = 5, SECONDLY = 6;
16
+ const WEEKDAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
17
+ const DAY = 86400000;
18
+ const SUB_UNIT = [0, 0, 0, 0, 3600000, 60000, 1000];
19
+ const list = (v, name, min, max, zero = true) => {
20
+ if (v === undefined)
21
+ return undefined;
22
+ const arr = (Array.isArray(v) ? v : [v]).map(Number);
23
+ for (const n of arr) {
24
+ if (!Number.isInteger(n) || Math.abs(n) > max || (min >= 0 && n < min) || (!zero && n === 0) || (min < 0 && n < min)) {
25
+ throw new RangeError(`neram: ${name} value ${n} is out of range`);
26
+ }
27
+ }
28
+ return arr.length ? [...new Set(arr)].sort((a, b) => a - b) : undefined;
29
+ };
30
+ function parseByDay(v) {
31
+ if (typeof v === 'object') {
32
+ const w = WEEKDAYS.indexOf(v.day.toUpperCase());
33
+ if (w < 0)
34
+ throw new RangeError(`neram: invalid weekday "${v.day}"`);
35
+ return { w, n: v.n ?? 0 };
36
+ }
37
+ const m = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/i.exec(v.trim());
38
+ if (!m)
39
+ throw new RangeError(`neram: invalid BYDAY "${v}"`);
40
+ const n = m[1] ? Number(m[1]) : 0;
41
+ if (Math.abs(n) > 53)
42
+ throw new RangeError(`neram: invalid BYDAY "${v}"`);
43
+ return { w: WEEKDAYS.indexOf(m[2].toUpperCase()), n };
44
+ }
45
+ const dayNum = (y, M, D) => Math.floor(utcFromParts(y, M, D) / DAY);
46
+ const fromDay = civilFromDays;
47
+ function wallOf(ms) {
48
+ const w = wallOfMs(ms);
49
+ return { y: w.y, M: w.M, D: w.D, h: w.h, m: w.m, s: w.s, ms: 0 };
50
+ }
51
+ const isDateOnly = (v) => typeof v === 'string' && /^\d{4}-?\d{2}-?\d{2}$/.test(v.trim());
52
+ // ---------------------------------------------------------------------------
53
+ // RRule
54
+ // ---------------------------------------------------------------------------
55
+ export class RRule extends Schedule {
56
+ tz;
57
+ allDay;
58
+ #o;
59
+ #eff;
60
+ #dtWallMs;
61
+ #dtMs;
62
+ #dt;
63
+ #exdates;
64
+ #rdates;
65
+ constructor(opts) {
66
+ super();
67
+ for (const key of Object.keys(opts)) {
68
+ if (!OPTION_KEYS.has(key)) {
69
+ const hint = [...OPTION_KEYS].find((k) => k.toLowerCase() === key.toLowerCase());
70
+ throw new RangeError(`neram: unknown rrule option "${key}"${hint ? `; did you mean "${hint}"?` : ''}`);
71
+ }
72
+ }
73
+ const freq = FREQS.indexOf(String(opts.freq).toLowerCase());
74
+ if (freq < 0)
75
+ throw new RangeError(`neram: invalid freq "${opts.freq}"`);
76
+ if (opts.dtstart === undefined || opts.dtstart === null)
77
+ throw new RangeError('neram: dtstart is required');
78
+ let start = opts.tz ? neram(opts.dtstart, { zone: opts.tz }) : neram(opts.dtstart);
79
+ if (!start.isValid())
80
+ throw new RangeError(`neram: invalid dtstart ${JSON.stringify(opts.dtstart)}`);
81
+ this.tz = normalizeZone(opts.tz ?? start.timezone());
82
+ this.allDay = opts.allDay ?? false;
83
+ start = start.tz(this.tz).millisecond(0);
84
+ if (this.allDay)
85
+ start = start.startOf('day');
86
+ const [y, M, D, h, m, s] = start.toArray();
87
+ this.#dt = { y, M, D, h, m, s, dow: start.day() };
88
+ this.#dtWallMs = utcFromParts(y, M, D, h, m, s);
89
+ this.#dtMs = start.valueOf();
90
+ const interval = opts.interval ?? 1;
91
+ if (!Number.isInteger(interval) || interval < 1)
92
+ throw new RangeError('neram: interval must be a positive integer');
93
+ if (opts.count !== undefined && (!Number.isInteger(opts.count) || opts.count < 1)) {
94
+ throw new RangeError('neram: count must be a positive integer');
95
+ }
96
+ if (opts.count !== undefined && opts.until !== undefined && opts.until !== null) {
97
+ throw new RangeError('neram: use count or until, not both (RFC 5545)');
98
+ }
99
+ let wkst = 1;
100
+ if (opts.wkst) {
101
+ wkst = WEEKDAYS.indexOf(opts.wkst.toUpperCase());
102
+ if (wkst < 0)
103
+ throw new RangeError(`neram: invalid wkst "${opts.wkst}"`);
104
+ }
105
+ let untilMs;
106
+ if (opts.until !== undefined && opts.until !== null) {
107
+ const u = neram(opts.until, { zone: this.tz });
108
+ if (!u.isValid())
109
+ throw new RangeError(`neram: invalid until ${JSON.stringify(opts.until)}`);
110
+ untilMs = (this.allDay || isDateOnly(opts.until) ? u.endOf('day') : u).valueOf();
111
+ }
112
+ const byDay = opts.byDay === undefined ? undefined : (Array.isArray(opts.byDay) ? opts.byDay : [opts.byDay]).map(parseByDay);
113
+ if (byDay?.some((r) => r.n !== 0)) {
114
+ // RFC 5545: "1MO" (first Monday) only means something within a month or a year.
115
+ if (freq !== MONTHLY && freq !== YEARLY) {
116
+ throw new RangeError(`neram: byDay with a number ("1MO", "-1FR") needs freq 'monthly' or 'yearly'`);
117
+ }
118
+ if (freq === YEARLY && opts.byWeekNo !== undefined) {
119
+ throw new RangeError('neram: byDay with a number cannot be combined with byWeekNo (RFC 5545)');
120
+ }
121
+ }
122
+ this.#o = {
123
+ freq,
124
+ interval,
125
+ count: opts.count,
126
+ untilMs,
127
+ wkst,
128
+ wkstGiven: opts.wkst !== undefined,
129
+ byMonth: list(opts.byMonth, 'byMonth', 1, 12),
130
+ byWeekNo: list(opts.byWeekNo, 'byWeekNo', -53, 53, false),
131
+ byYearDay: list(opts.byYearDay, 'byYearDay', -366, 366, false),
132
+ byMonthDay: list(opts.byMonthDay, 'byMonthDay', -31, 31, false),
133
+ byDay: byDay?.length ? byDay : undefined,
134
+ byHour: list(opts.byHour, 'byHour', 0, 23),
135
+ byMinute: list(opts.byMinute, 'byMinute', 0, 59),
136
+ bySecond: list(opts.bySecond, 'bySecond', 0, 60),
137
+ bySetPos: list(opts.bySetPos, 'bySetPos', -366, 366, false),
138
+ };
139
+ // RFC 5545 defaults: missing BYxxx parts are taken from DTSTART.
140
+ const e = { ...this.#o };
141
+ const noDayParts = !e.byWeekNo && !e.byYearDay && !e.byMonthDay && !e.byDay;
142
+ if (freq === YEARLY && noDayParts) {
143
+ e.byMonth ??= [M + 1];
144
+ e.byMonthDay = [D];
145
+ }
146
+ else if (freq === MONTHLY && noDayParts) {
147
+ e.byMonthDay = [D];
148
+ }
149
+ else if (freq === WEEKLY && !e.byDay && !e.byMonthDay && !e.byYearDay) {
150
+ e.byDay = [{ w: this.#dt.dow, n: 0 }];
151
+ }
152
+ if (this.allDay) {
153
+ e.byHour = [0];
154
+ e.byMinute = [0];
155
+ e.bySecond = [0];
156
+ }
157
+ else {
158
+ if (freq < HOURLY)
159
+ e.byHour ??= [h];
160
+ if (freq < MINUTELY)
161
+ e.byMinute ??= [m];
162
+ if (freq < SECONDLY)
163
+ e.bySecond ??= [s];
164
+ }
165
+ this.#eff = e;
166
+ const toMs = (d) => {
167
+ const n = neram(d, { zone: this.tz });
168
+ if (!n.isValid())
169
+ throw new RangeError(`neram: invalid date ${JSON.stringify(d)}`);
170
+ return (this.allDay ? n.startOf('day') : n.millisecond(0)).valueOf();
171
+ };
172
+ this.#exdates = new Set((opts.exdate ?? []).map(toMs));
173
+ this.#rdates = [...new Set((opts.rdate ?? []).map(toMs))].sort((a, b) => a - b);
174
+ }
175
+ isInfinite() {
176
+ return this.#o.count === undefined && this.#o.untilMs === undefined;
177
+ }
178
+ startMs() {
179
+ return Math.min(this.#dtMs, this.#rdates[0] ?? Infinity);
180
+ }
181
+ get freq() {
182
+ return FREQS[this.#o.freq];
183
+ }
184
+ /** The first occurrence's start, in the rule's zone. */
185
+ get dtstart() {
186
+ return neram(this.#dtMs, { zone: this.tz });
187
+ }
188
+ // -- expansion -------------------------------------------------------------
189
+ #matchDay(dn, periodYear) {
190
+ const e = this.#eff;
191
+ const { y, M, D, dow } = fromDay(dn);
192
+ if (e.byMonth && !e.byMonth.includes(M + 1))
193
+ return false;
194
+ if (e.byWeekNo) {
195
+ const wk = weekOfYear(y, M, D, e.wkst, 4);
196
+ if (e.freq === YEARLY && wk.year !== periodYear)
197
+ return false;
198
+ const nw = weeksInYear(wk.year, e.wkst, 4);
199
+ if (!e.byWeekNo.some((n) => (n > 0 ? n : nw + n + 1) === wk.week))
200
+ return false;
201
+ }
202
+ if (e.byYearDay) {
203
+ const doy = dayOfYear(y, M, D);
204
+ const diy = daysInYear(y);
205
+ if (!e.byYearDay.some((n) => (n > 0 ? n : diy + n + 1) === doy))
206
+ return false;
207
+ }
208
+ if (e.byMonthDay) {
209
+ const dim = daysInMonth(y, M);
210
+ if (!e.byMonthDay.some((n) => (n > 0 ? n : dim + n + 1) === D))
211
+ return false;
212
+ }
213
+ if (e.byDay) {
214
+ const monthScope = e.freq === MONTHLY || (e.freq === YEARLY && !!e.byMonth);
215
+ const yearScope = e.freq === YEARLY && !e.byMonth;
216
+ let ok = false;
217
+ for (const r of e.byDay) {
218
+ if (r.w !== dow)
219
+ continue;
220
+ if (r.n === 0 || (!monthScope && !yearScope)) {
221
+ ok = true;
222
+ break;
223
+ }
224
+ let idx, last;
225
+ if (monthScope) {
226
+ idx = Math.floor((D - 1) / 7) + 1;
227
+ last = -(Math.floor((daysInMonth(y, M) - D) / 7) + 1);
228
+ }
229
+ else {
230
+ const doy = dayOfYear(y, M, D);
231
+ idx = Math.floor((doy - 1) / 7) + 1;
232
+ last = -(Math.floor((daysInYear(y) - doy) / 7) + 1);
233
+ }
234
+ if (r.n === idx || r.n === last) {
235
+ ok = true;
236
+ break;
237
+ }
238
+ }
239
+ if (!ok)
240
+ return false;
241
+ }
242
+ return true;
243
+ }
244
+ #times() {
245
+ const e = this.#eff;
246
+ const out = [];
247
+ for (const h of e.byHour)
248
+ for (const m of e.byMinute)
249
+ for (const s of e.bySecond) {
250
+ out.push(h * 3600000 + m * 60000 + s * 1000);
251
+ }
252
+ return out.sort((a, b) => a - b);
253
+ }
254
+ /** Candidate wall times (as UTC-ms of the wall clock) for period p. */
255
+ #period(p, times) {
256
+ const e = this.#eff;
257
+ const dt = this.#dt;
258
+ const iv = e.interval;
259
+ let first, last, year;
260
+ if (e.freq >= HOURLY) {
261
+ const unit = SUB_UNIT[e.freq];
262
+ const base = this.#dtWallMs - (((this.#dtWallMs % unit) + unit) % unit);
263
+ const pw = base + p * iv * unit;
264
+ const dn = Math.floor(pw / DAY);
265
+ year = fromDay(dn).y;
266
+ const jump = (to) => Math.ceil((to - base) / (iv * unit));
267
+ if (!this.#matchDay(dn, year))
268
+ return { year, walls: [], skipTo: jump((dn + 1) * DAY) };
269
+ const w = wallOf(pw);
270
+ if (e.byHour && !e.byHour.includes(w.h)) {
271
+ return e.freq === HOURLY ? { year, walls: [] } : { year, walls: [], skipTo: jump((Math.floor(pw / 3600000) + 1) * 3600000) };
272
+ }
273
+ if (e.freq === SECONDLY && e.byMinute && !e.byMinute.includes(w.m)) {
274
+ return { year, walls: [], skipTo: jump((Math.floor(pw / 60000) + 1) * 60000) };
275
+ }
276
+ const walls = [];
277
+ if (e.freq === HOURLY) {
278
+ for (const m of e.byMinute ?? [dt.m])
279
+ for (const s of e.bySecond ?? [dt.s])
280
+ walls.push(pw + m * 60000 + s * 1000);
281
+ }
282
+ else if (e.freq === MINUTELY) {
283
+ if (e.byMinute && !e.byMinute.includes(w.m))
284
+ return { year, walls: [] };
285
+ for (const s of e.bySecond ?? [dt.s])
286
+ walls.push(pw + s * 1000);
287
+ }
288
+ else if (!e.bySecond || e.bySecond.includes(w.s)) {
289
+ walls.push(pw);
290
+ }
291
+ return { year, walls: walls.sort((a, b) => a - b) };
292
+ }
293
+ switch (e.freq) {
294
+ case YEARLY:
295
+ year = dt.y + p * iv;
296
+ first = e.byWeekNo ? dayNum(year - 1, 11, 25) : dayNum(year, 0, 1);
297
+ last = e.byWeekNo ? dayNum(year + 1, 0, 7) : dayNum(year, 11, 31);
298
+ break;
299
+ case MONTHLY: {
300
+ const total = dt.y * 12 + dt.M + p * iv;
301
+ year = Math.floor(total / 12);
302
+ const M = total - year * 12;
303
+ first = dayNum(year, M, 1);
304
+ last = dayNum(year, M, daysInMonth(year, M));
305
+ break;
306
+ }
307
+ case WEEKLY: {
308
+ const d0 = dayNum(dt.y, dt.M, dt.D);
309
+ first = d0 - ((dt.dow - e.wkst + 7) % 7) + p * iv * 7;
310
+ last = first + 6;
311
+ year = fromDay(first).y;
312
+ break;
313
+ }
314
+ default: // DAILY
315
+ first = last = dayNum(dt.y, dt.M, dt.D) + p * iv;
316
+ year = fromDay(first).y;
317
+ }
318
+ const walls = [];
319
+ for (let dn = first; dn <= last; dn++) {
320
+ if (!this.#matchDay(dn, year))
321
+ continue;
322
+ for (const t of times)
323
+ walls.push(dn * DAY + t);
324
+ }
325
+ return { year, walls };
326
+ }
327
+ #seek(fromMs) {
328
+ const e = this.#eff;
329
+ const dt = this.#dt;
330
+ const target = neram(fromMs - 2 * DAY, { zone: this.tz });
331
+ const [ty, tM, tD, th, tm, ts] = target.toArray();
332
+ const iv = e.interval;
333
+ let p;
334
+ switch (e.freq) {
335
+ case YEARLY:
336
+ p = Math.floor((ty - dt.y) / iv) - 1;
337
+ break;
338
+ case MONTHLY:
339
+ p = Math.floor((ty * 12 + tM - (dt.y * 12 + dt.M)) / iv) - 1;
340
+ break;
341
+ case WEEKLY: {
342
+ const ws0 = dayNum(dt.y, dt.M, dt.D) - ((dt.dow - e.wkst + 7) % 7);
343
+ p = Math.floor((dayNum(ty, tM, tD) - ws0) / (7 * iv)) - 1;
344
+ break;
345
+ }
346
+ case DAILY:
347
+ p = Math.floor((dayNum(ty, tM, tD) - dayNum(dt.y, dt.M, dt.D)) / iv) - 1;
348
+ break;
349
+ default: {
350
+ const unit = SUB_UNIT[e.freq];
351
+ const base = this.#dtWallMs - (((this.#dtWallMs % unit) + unit) % unit);
352
+ p = Math.floor((utcFromParts(ty, tM, tD, th, tm, ts) - base) / (iv * unit)) - 1;
353
+ }
354
+ }
355
+ return Math.max(0, p);
356
+ }
357
+ /** Instants produced by the RRULE part alone (COUNT counts these). */
358
+ *#rule(fromMs) {
359
+ const e = this.#eff;
360
+ const times = e.freq < HOURLY ? this.#times() : [];
361
+ const seeking = e.count === undefined && Number.isFinite(fromMs) && fromMs > this.#dtMs;
362
+ let p = seeking ? this.#seek(fromMs) : 0;
363
+ let lastHitYear = seeking ? neram(fromMs, { zone: this.tz }).year() : this.#dt.y;
364
+ let emitted = 0;
365
+ let lastInst = -Infinity;
366
+ for (;; p++) {
367
+ const res = this.#period(p, times);
368
+ if (res.year > 9999 || res.year > lastHitYear + 400)
369
+ return;
370
+ if (res.skipTo !== undefined) {
371
+ p = res.skipTo - 1;
372
+ continue;
373
+ }
374
+ let walls = res.walls;
375
+ if (e.bySetPos && walls.length) {
376
+ const n = walls.length;
377
+ walls = [...new Set(e.bySetPos.map((i) => walls[i > 0 ? i - 1 : n + i]).filter((x) => x !== undefined))].sort((a, b) => a - b);
378
+ }
379
+ for (const wt of walls) {
380
+ if (wt < this.#dtWallMs)
381
+ continue;
382
+ const inst = wallToEpoch(wallOf(wt), this.tz);
383
+ if (e.untilMs !== undefined && inst > e.untilMs)
384
+ return;
385
+ if (inst <= lastInst)
386
+ continue; // a skipped DST hour mapped onto an existing instant
387
+ lastInst = inst;
388
+ lastHitYear = res.year;
389
+ emitted++;
390
+ if (inst >= fromMs)
391
+ yield inst;
392
+ if (e.count !== undefined && emitted >= e.count)
393
+ return;
394
+ }
395
+ }
396
+ }
397
+ /** RRULE ∪ RDATE − EXDATE, ascending. */
398
+ *iterate(fromMs) {
399
+ const rd = this.#rdates.filter((r) => r >= fromMs);
400
+ let i = 0;
401
+ let last = -Infinity;
402
+ const emit = (ms) => {
403
+ if (ms === last || this.#exdates.has(ms))
404
+ return false;
405
+ last = ms;
406
+ return true;
407
+ };
408
+ for (const ms of this.#rule(fromMs)) {
409
+ while (i < rd.length && rd[i] <= ms) {
410
+ if (emit(rd[i]))
411
+ yield rd[i];
412
+ i++;
413
+ }
414
+ if (emit(ms))
415
+ yield ms;
416
+ }
417
+ for (; i < rd.length; i++)
418
+ if (emit(rd[i]))
419
+ yield rd[i];
420
+ }
421
+ // -- serialisation ---------------------------------------------------------
422
+ #ical(ms) {
423
+ const d = neram(ms, { zone: this.tz });
424
+ if (this.allDay)
425
+ return d.format('YYYYMMDD');
426
+ if (this.tz === 'UTC')
427
+ return d.format('YYYYMMDD[T]HHmmss[Z]');
428
+ return d.format('YYYYMMDD[T]HHmmss');
429
+ }
430
+ #dateProp(name, values) {
431
+ const params = this.allDay ? ';VALUE=DATE' : this.tz === 'UTC' ? '' : `;TZID=${this.tz}`;
432
+ return `${name}${params}:${values.map((v) => this.#ical(v)).join(',')}`;
433
+ }
434
+ /** The RRULE line alone: "FREQ=WEEKLY;BYDAY=MO,WE;COUNT=10" */
435
+ rruleString() {
436
+ const o = this.#o;
437
+ const parts = [`FREQ=${FREQS[o.freq].toUpperCase()}`];
438
+ if (o.interval !== 1)
439
+ parts.push(`INTERVAL=${o.interval}`);
440
+ if (o.count !== undefined)
441
+ parts.push(`COUNT=${o.count}`);
442
+ if (o.untilMs !== undefined) {
443
+ const u = neram(o.untilMs, { zone: this.allDay ? this.tz : 'UTC' });
444
+ parts.push(`UNTIL=${this.allDay ? u.format('YYYYMMDD') : u.format('YYYYMMDD[T]HHmmss[Z]')}`);
445
+ }
446
+ if (o.wkstGiven)
447
+ parts.push(`WKST=${WEEKDAYS[o.wkst]}`);
448
+ const add = (k, v) => v && parts.push(`${k}=${v.join(',')}`);
449
+ add('BYMONTH', o.byMonth);
450
+ add('BYWEEKNO', o.byWeekNo);
451
+ add('BYYEARDAY', o.byYearDay);
452
+ add('BYMONTHDAY', o.byMonthDay);
453
+ add('BYDAY', o.byDay?.map((r) => `${r.n || ''}${WEEKDAYS[r.w]}`));
454
+ add('BYHOUR', o.byHour);
455
+ add('BYMINUTE', o.byMinute);
456
+ add('BYSECOND', o.bySecond);
457
+ add('BYSETPOS', o.bySetPos);
458
+ return parts.join(';');
459
+ }
460
+ /**
461
+ * RFC 5545 text — store this in your database and load it back with rrule(text).
462
+ * DTSTART;TZID=Asia/Kolkata:20261207T090000
463
+ * RRULE:FREQ=WEEKLY;BYDAY=MO,WE
464
+ * EXDATE;TZID=Asia/Kolkata:20261209T090000
465
+ */
466
+ toString() {
467
+ const lines = [this.#dateProp('DTSTART', [this.#dtMs]), `RRULE:${this.rruleString()}`];
468
+ if (this.#rdates.length)
469
+ lines.push(this.#dateProp('RDATE', this.#rdates));
470
+ if (this.#exdates.size)
471
+ lines.push(this.#dateProp('EXDATE', [...this.#exdates].sort((a, b) => a - b)));
472
+ return lines.join('\n');
473
+ }
474
+ /** Plain-object form with zoned ISO strings; rrule(json) restores it. */
475
+ toJSON() {
476
+ const o = this.#o;
477
+ const z = (ms) => {
478
+ const d = neram(ms, { zone: this.tz });
479
+ return this.allDay ? d.format('YYYY-MM-DD') : d.toZonedISOString();
480
+ };
481
+ const out = { freq: FREQS[o.freq], dtstart: z(this.#dtMs), tz: this.tz };
482
+ if (this.allDay)
483
+ out.allDay = true;
484
+ if (o.interval !== 1)
485
+ out.interval = o.interval;
486
+ if (o.count !== undefined)
487
+ out.count = o.count;
488
+ if (o.untilMs !== undefined)
489
+ out.until = z(o.untilMs);
490
+ if (o.wkstGiven)
491
+ out.wkst = WEEKDAYS[o.wkst];
492
+ for (const k of ['byMonth', 'byWeekNo', 'byYearDay', 'byMonthDay', 'byHour', 'byMinute', 'bySecond', 'bySetPos']) {
493
+ if (o[k])
494
+ out[k] = [...o[k]];
495
+ }
496
+ if (o.byDay)
497
+ out.byDay = o.byDay.map((r) => `${r.n || ''}${WEEKDAYS[r.w]}`);
498
+ if (this.#rdates.length)
499
+ out.rdate = this.#rdates.map(z);
500
+ if (this.#exdates.size)
501
+ out.exdate = [...this.#exdates].sort((a, b) => a - b).map(z);
502
+ return out;
503
+ }
504
+ /** A copy with some options changed: rule.with({ exdate: [...] }) */
505
+ with(changes) {
506
+ const base = this.toJSON();
507
+ // A new ending replaces the old one: setting until drops count, and the other way round.
508
+ if ('until' in changes)
509
+ delete base.count;
510
+ if ('count' in changes)
511
+ delete base.until;
512
+ return new RRule({ ...base, ...changes });
513
+ }
514
+ /**
515
+ * Plain-English description: "every 2 weeks on Monday and Wednesday at 9:00 AM, 10 times".
516
+ * Weekday, month and time names follow `locale`; the sentence itself is English.
517
+ */
518
+ toText(locale = 'en') {
519
+ const o = this.#o;
520
+ const ld = localeData(locale);
521
+ const listFmt = (xs) => formatList(xs, 'en');
522
+ const unit = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second'][o.freq];
523
+ const ORD = { 1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth', [-1]: 'last', [-2]: 'second-to-last' };
524
+ let text = o.interval === 1 ? `every ${unit}` : `every ${o.interval} ${unit}s`;
525
+ if (o.freq === DAILY && o.byDay && o.byDay.every((r) => !r.n)) {
526
+ const set = o.byDay.map((r) => r.w).sort().join();
527
+ if (set === '1,2,3,4,5' && o.interval === 1)
528
+ text = 'every weekday';
529
+ }
530
+ if (o.byMonth)
531
+ text += ` in ${listFmt(o.byMonth.map((m) => ld.months[m - 1]))}`;
532
+ // Parts RFC 5545 takes from DTSTART: say them out loud.
533
+ const noDayParts = !o.byWeekNo && !o.byYearDay && !o.byMonthDay && !o.byDay;
534
+ const dt = this.#dt;
535
+ if (noDayParts && o.freq === YEARLY && !o.byMonth)
536
+ text += ` on ${ld.months[dt.M]} ${dt.D}`;
537
+ else if (noDayParts && o.freq === YEARLY)
538
+ text += ` on the ${ordinal(dt.D, 'en')}`;
539
+ else if (noDayParts && o.freq === MONTHLY)
540
+ text += ` on the ${ordinal(dt.D, 'en')}`;
541
+ else if (o.freq === WEEKLY && !o.byDay && !o.byMonthDay && !o.byYearDay)
542
+ text += ` on ${ld.weekdays[dt.dow]}`;
543
+ if (o.byWeekNo)
544
+ text += ` in week ${listFmt(o.byWeekNo.map(String))}`;
545
+ if (o.byYearDay)
546
+ text += ` on day ${listFmt(o.byYearDay.map(String))} of the year`;
547
+ if (o.byMonthDay) {
548
+ text += ` on the ${listFmt(o.byMonthDay.map((d) => (d === -1 ? 'last day' : d < 0 ? `${ordinal(-d, 'en')}-to-last day` : ordinal(d, 'en'))))}`;
549
+ }
550
+ const plainDays = o.byDay && o.byDay.every((r) => !r.n);
551
+ const isWorkweek = plainDays && o.byDay.map((r) => r.w).sort().join() === '1,2,3,4,5';
552
+ if (o.bySetPos && plainDays && !o.byMonthDay) {
553
+ // "the last weekday of the month", "the first Saturday or Sunday"
554
+ const what = isWorkweek ? 'weekday' : formatList(o.byDay.map((r) => ld.weekdays[r.w]), 'en', 'disjunction');
555
+ text += ` on the ${listFmt(o.bySetPos.map((n) => ORD[n] ?? ordinal(n, 'en')))} ${what}`;
556
+ }
557
+ else {
558
+ if (o.byDay && text !== 'every weekday') {
559
+ const days = o.byDay.map((r) => (r.n ? `${ORD[r.n] ?? ordinal(Math.abs(r.n), 'en') + (r.n < 0 ? ' last' : '')} ` : '') + ld.weekdays[r.w]);
560
+ text += `${o.byMonthDay ? ' if it is' : ' on'} ${o.byDay.some((r) => r.n) ? 'the ' : ''}${listFmt(days)}`;
561
+ }
562
+ if (o.bySetPos)
563
+ text += ` (occurrence ${listFmt(o.bySetPos.map(String))} of each ${unit})`;
564
+ }
565
+ if (!this.allDay && o.freq <= DAILY) {
566
+ const e = this.#eff;
567
+ const times = this.#times().slice(0, 6).map((t) => {
568
+ const ms = utcFromParts(2000, 0, 1) + t;
569
+ return neram(ms, { zone: 'UTC', locale }).format(e.bySecond.some((s) => s) ? 'LTS' : 'LT');
570
+ });
571
+ text += ` at ${listFmt(times)}`;
572
+ }
573
+ if (o.untilMs !== undefined)
574
+ text += ` until ${neram(o.untilMs, { zone: this.tz, locale }).format('LL')}`;
575
+ if (o.count !== undefined)
576
+ text += `, ${o.count} time${o.count === 1 ? '' : 's'}`;
577
+ return text;
578
+ }
579
+ }
580
+ // ---------------------------------------------------------------------------
581
+ // Parsing RFC 5545 text
582
+ // ---------------------------------------------------------------------------
583
+ const ICAL_DATE = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/i;
584
+ function icalDate(v, tz) {
585
+ const m = ICAL_DATE.exec(v.trim());
586
+ if (!m)
587
+ throw new RangeError(`neram: invalid iCalendar date "${v}"`);
588
+ const dateOnly = !m[4];
589
+ const iso = dateOnly ? `${m[1]}-${m[2]}-${m[3]}` : `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}`;
590
+ const utc = !!m[7];
591
+ const value = utc ? neram(`${iso}Z`, { zone: tz ?? 'UTC' }) : neram(iso, { zone: tz ?? 'UTC' });
592
+ return { value, dateOnly, utc };
593
+ }
594
+ /**
595
+ * Parse RFC 5545 text into options. Accepts a full block (DTSTART / RRULE / RDATE / EXDATE lines)
596
+ * or a bare "FREQ=…" / "RRULE:FREQ=…" line, in which case pass dtstart in `defaults`.
597
+ */
598
+ export function parseRRule(text, defaults = {}) {
599
+ const lines = text.replace(/\r?\n[ \t]/g, '').split(/\r?\n|\\n/).map((l) => l.trim()).filter(Boolean);
600
+ const opts = {};
601
+ let tz = defaults.tz;
602
+ let sawRule = false;
603
+ const rdate = [];
604
+ const exdate = [];
605
+ const dated = [];
606
+ for (const line of lines) {
607
+ const colon = line.indexOf(':');
608
+ const isBare = colon < 0 || /^FREQ=/i.test(line);
609
+ const head = isBare ? 'RRULE' : line.slice(0, colon);
610
+ const value = isBare ? line : line.slice(colon + 1);
611
+ const [name, ...rawParams] = head.split(';');
612
+ const params = {};
613
+ for (const p of rawParams) {
614
+ const eq = p.indexOf('=');
615
+ params[p.slice(0, eq).toUpperCase()] = p.slice(eq + 1).replace(/^"|"$/g, '');
616
+ }
617
+ const N = name.toUpperCase();
618
+ if (N === 'RRULE') {
619
+ if (sawRule)
620
+ throw new RangeError('neram: only one RRULE per rule is supported; use several rules for more');
621
+ sawRule = true;
622
+ for (const part of value.split(';').filter(Boolean)) {
623
+ const eq = part.indexOf('=');
624
+ if (eq < 1)
625
+ throw new RangeError(`neram: invalid RRULE part "${part}"`);
626
+ const k = part.slice(0, eq).toUpperCase();
627
+ const v = part.slice(eq + 1);
628
+ const nums = () => v.split(',').map(Number);
629
+ switch (k) {
630
+ case 'FREQ':
631
+ opts.freq = v.toLowerCase();
632
+ break;
633
+ case 'INTERVAL':
634
+ opts.interval = Number(v);
635
+ break;
636
+ case 'COUNT':
637
+ opts.count = Number(v);
638
+ break;
639
+ case 'UNTIL':
640
+ opts.until = v;
641
+ break; // resolved below, once the zone is known
642
+ case 'WKST':
643
+ opts.wkst = v.toUpperCase();
644
+ break;
645
+ case 'BYMONTH':
646
+ opts.byMonth = nums();
647
+ break;
648
+ case 'BYWEEKNO':
649
+ opts.byWeekNo = nums();
650
+ break;
651
+ case 'BYYEARDAY':
652
+ opts.byYearDay = nums();
653
+ break;
654
+ case 'BYMONTHDAY':
655
+ opts.byMonthDay = nums();
656
+ break;
657
+ case 'BYDAY':
658
+ opts.byDay = v.split(',');
659
+ break;
660
+ case 'BYHOUR':
661
+ opts.byHour = nums();
662
+ break;
663
+ case 'BYMINUTE':
664
+ opts.byMinute = nums();
665
+ break;
666
+ case 'BYSECOND':
667
+ opts.bySecond = nums();
668
+ break;
669
+ case 'BYSETPOS':
670
+ opts.bySetPos = nums();
671
+ break;
672
+ default:
673
+ if (k.startsWith('X-'))
674
+ break; // extensions are allowed and ignored
675
+ throw new RangeError(`neram: unsupported RRULE part "${k}"`);
676
+ }
677
+ }
678
+ }
679
+ else if (N === 'DTSTART' || N === 'RDATE' || N === 'EXDATE') {
680
+ dated.push({ name: N, params, values: value.split(',') });
681
+ }
682
+ }
683
+ for (const d of dated) {
684
+ if (d.name !== 'DTSTART')
685
+ continue;
686
+ if (d.params.TZID)
687
+ tz ??= d.params.TZID;
688
+ const parsed = icalDate(d.values[0], tz);
689
+ if (parsed.utc && !tz)
690
+ tz = 'UTC';
691
+ opts.dtstart = parsed.value;
692
+ if (parsed.dateOnly || d.params.VALUE?.toUpperCase() === 'DATE')
693
+ opts.allDay = true;
694
+ }
695
+ for (const d of dated) {
696
+ if (d.name === 'DTSTART')
697
+ continue;
698
+ const zone = d.params.TZID ?? tz;
699
+ for (const v of d.values)
700
+ (d.name === 'RDATE' ? rdate : exdate).push(icalDate(v, zone).value);
701
+ }
702
+ if (typeof opts.until === 'string') {
703
+ const parsed = icalDate(opts.until, tz);
704
+ opts.until = parsed.dateOnly ? parsed.value.format('YYYY-MM-DD') : parsed.value;
705
+ }
706
+ if (!sawRule && !defaults.freq)
707
+ throw new RangeError('neram: no RRULE found');
708
+ if (sawRule && opts.freq === undefined && !defaults.freq)
709
+ throw new RangeError('neram: RRULE has no FREQ');
710
+ const merged = { ...opts, ...defaults };
711
+ if (tz)
712
+ merged.tz = tz;
713
+ if (rdate.length || defaults.rdate)
714
+ merged.rdate = [...rdate, ...(defaults.rdate ?? [])];
715
+ if (exdate.length || defaults.exdate)
716
+ merged.exdate = [...exdate, ...(defaults.exdate ?? [])];
717
+ if (merged.dtstart === undefined)
718
+ throw new RangeError('neram: no DTSTART; pass { dtstart } as the second argument');
719
+ return merged;
720
+ }
721
+ /**
722
+ * Create a recurrence rule from options, RFC 5545 text, or a stored toJSON() object.
723
+ * rrule({ freq: 'weekly', byDay: ['MO', 'WE'], dtstart: '2026-12-07 09:00', tz: 'Asia/Kolkata' })
724
+ * rrule('DTSTART;TZID=Asia/Kolkata:20261207T090000\nRRULE:FREQ=WEEKLY;BYDAY=MO,WE')
725
+ * rrule('FREQ=DAILY;COUNT=5', { dtstart: '2026-12-07 09:00', tz: 'UTC' })
726
+ */
727
+ export function rrule(input, defaults = {}) {
728
+ if (typeof input === 'string')
729
+ return new RRule(parseRRule(input, defaults));
730
+ return new RRule({ ...input, ...defaults });
731
+ }